How to Code With No Loops

What does a loop do exactly?

Why doesn't functional programming use loops?

  1. Pure Functions
sumArray(arr) {     
sum = 0
for(let num of arr) sum += num
return sum

So what do we do with no loops?


printNTimes 0 = return ()
printNTimes n =
putStrLn "hello world"
printNTimes (n-1)
allSquares :: Num a => [a] -> [a]
allSquares [] = []
allSquares (x : xs) = x * x : allSquares xs

Higher-Order Functions

  • map: used to transform each element of a collection. It won't change the type or length of your collection.
let xs = [1..20]
mapM_ print xs
  • filter: used to return elements of a collection that meet certain criteria. This new subset can be of a different length than the original collection.
beginsWithA (c:_) = c == 'a'
beginsWithA _ = False

myStringFilter xs = filter (not . beginsWithA) (map tail xs)
  • fold: used to accumulate, aggregate, or reduce a collection to a return value
sumArray :: Num a => [a] -> a
sumArray xs = foldl (\acc x -> acc + x) 0 xs




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store