Elm Language Lists and Iteration Reducing a list to a single value


Example

In Elm, reducing functions are called "folds", and there are two standard methods to "fold" values up: from the left, foldl, and from the right, foldr.

> List.foldl (+) 0 [1,2,3]
6 : number

The arguments to foldl and foldr are:

  • reducing function: newValue -> accumulator -> accumulator
  • accumulator starting value
  • list to reduce

One more example with custom function:

type alias Counts =
    { odd : Int
    , even : Int
    }

addCount : Int -> Counts -> Counts
addCount num counts =
    let
        (incOdd, incEven) =
            if num `rem` 2 == 0
                then (0,1)
                else (1,0)
    in
        { counts
            | odd = counts.odd + incOdd
            , even = counts.even + incEven
        }

> List.foldl
      addCount
      { odd = 0, even = 0 }
      [1,2,3,4,5]
{ odd = 3, even = 2 } : Counts

In the first example above the program goes like this:

List.foldl (+) 0 [1,2,3]
3 + (2 + (1 + 0))
3 + (2 + 1)
3 + 3
6
List.foldr (+) 0 [1,2,3]
1 + (2 + (3 + 0))
1 + (2 + 3)
1 + 5
6

In the case of a commutative function like (+) there's not really a difference.

But see what happens with (::):

List.foldl (::) [] [1,2,3]
3 :: (2 :: (1 :: []))
3 :: (2 :: [1])
3 :: [2,1]
[3,2,1]
List.foldr (::) [] [1,2,3]
1 :: (2 :: (3 :: []))
1 :: (2 :: [3])
1 :: [2,3]
[1,2,3]