Lesson 12 of 16

Folds

Folds

Folds reduce a list to a single value by repeatedly applying a function.

foldl

foldl processes left-to-right with an accumulator:

foldl (+) 0 [1,2,3,4,5]   -- 15
foldl (*) 1 [1..5]         -- 120

The signature: foldl :: (b -> a -> b) -> b -> [a] -> b

  • First arg: combining function (accumulator -> element -> new_accumulator)
  • Second arg: initial accumulator
  • Third arg: the list

The combining function is often written as an inline lambda using backslash notation (e.g., \acc x -> acc + x). The \ resembles the Greek letter lambda. We will cover lambdas in more detail in the next lesson.

foldr

foldr processes right-to-left:

foldr (:) [] [1,2,3]   -- [1,2,3]  (identity on lists)

Handy Shortcuts

sum and product are built on folds:

sum [1..100]      -- 5050
product [1..5]    -- 120

Your Task

Use foldl to compute the sum of squares of [1..5] (1 + 4 + 9 + 16 + 25 = 55). Print the result.

Haskell loading...
Loading...
Click "Run" to execute your code.