Left-associative fold over a list (strict: foldl').
foldl (fold left) reduces a list using a binary function, starting from the left end. Its type signature is (b -> a -> b) -> b -> [a] -> b. It processes elements left to right, threading an accumulator through each step. The expression foldl f z [x1, x2, x3] evaluates as f (f (f z x1) x2) x3.
The lazy version foldl can cause space leaks because it builds up a large thunk of unevaluated applications before computing the result. For this reason, the strict variant foldl' from Data.List (also re-exported by Prelude in modern GHC) is almost always preferred. foldl' evaluates the accumulator to weak head normal form at each step, preventing thunk buildup.
foldl is well-suited for accumulating a single result from a list, such as computing a sum, product, or building a reversed list. Unlike foldr, foldl cannot short-circuit or work with infinite lists because it must traverse the entire list before returning a result.
| Name | Description | Optional |
|---|---|---|
f |
A binary function (b -> a -> b) combining the accumulator with an element. | No |
z |
The initial accumulator value of type b. | No |
xs |
A list [a] to fold over from the left. | No |
foldl (+) 0 [1, 2, 3] -- 6
foldl (\acc x -> acc ++ [x]) [] [1, 2, 3] -- [1, 2, 3]
foldl' (+) 0 [1..1000000] -- 500000500000 (strict, no space leak)