DEV Community

Discussion on: Elm: the jerk that took away my for-loops.

Collapse
 
1hko profile image
1hko • Edited

List.map isn't the only way to "loop" in Elm. Recursion is the construct for repeating something in a functional language. If map didn't exist, you could easily write it on your own using recursion -

map : (a -> b) -> List a -> List b
map f list =
    case list of
        [] -> []
        first :: more -> (f first) :: map f more

> map (\n -> n * n) [ 1, 2, 3, 4 ]
-- [ 1, 4, 9, 16 ] : number

> map (\n -> String.repeat n "x") [ 1, 2, 3, 4 ]
-- [ "x", "xx", "xxx", "xxxx" ] : List String

This goes for any program where a "loop" is needed. In some procedural language, you might write the classic fibonacci program -

function fibonacci (n = 0) {
  let a = 0, b = 1, temp
  for (let m = 0; m < n; m++) {
    temp = a
    a = b
    b = temp + b
  }
  return a
}

> fibonacci(10)
// 55

> fibonacci(50)
// 12586269025

But in a functional language like Elm, we use recursion and avoid side-effects like variable mutation and reassignment. The result is a program that is much easier to think about -

fibonacci : Int -> Int
fibonacci n =
    helper n 0 1

helper : Int -> Int -> Int -> Int
helper n a b =
    case n of
        0 -> a
        _ -> helper (n - 1) b (a + b)

> fibonacci 10
-- 55 : Int

> fibonacci 50
-- 12586269025 : Int