🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Strict Folds

A strict fold is a fold that evaluates its running total at each step. It avoids building a tower of unevaluated additions while it works through a list.

A strict fold adds 1 through 100

The strict fold adds 1 through 100. The total is 5050.

import Data.List (foldl')
main :: IO ()
main = print (foldl' (+) 0 [1..100])

A strict fold multiplies a short list

The strict fold multiplies 1 through 5. The product is 120.

import Data.List (foldl')
main :: IO ()
main = print (foldl' (*) 1 [1,2,3,4,5])

A strict fold can count elements

Each step adds 1 and ignores the element itself. The count of three elements is 3.

import Data.List (foldl')
main :: IO ()
main = print (foldl' (\n _ -> n + 1) 0 [10,20,30])

Example

import Data.List (foldl')
main :: IO ()
main = do
  print (foldl' (+) 0 [1..100])
  print (foldl' (\n _ -> n + 1) 0 [1..100])

Key points

  • Foldl prime: foldl' from Data.List is the strict fold.
  • Running total: each step combines the total so far with the next element.
  • Same answer: foldl' gives the same result as foldl for ordinary values.
  • No tower: foldl' never leaves a long chain of additions waiting at the end.
  • Sum: foldl' (+) 0 adds a list strictly.

In this example, the first fold adds 1 through 100 strictly. The second fold counts the same list strictly, so it shows 100.

Note

use foldl' for ordinary left folds unless laziness is needed on purpose.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

Which fold should you use for an ordinary strict left fold?