HASKELL / CHAPTER 07
Fold direction, demand, and strictness
AdvancedChoose evaluation behavior as well as a combining operation.
By the end of this chapter
- Trace left and right fold association
- Use foldl' for strict scalar accumulation
- Recognize short-circuiting right folds
The idea
A fold combines a structure according to an association rule. Left and right folds can produce different results when the operation is not associative, such as subtraction. First expand a small example into parenthesized applications rather than assuming the functions are interchangeable. An identity value also determines the result for empty input.
Lazy foldl can build a chain of unevaluated accumulator expressions. Data.List.foldl' forces each new accumulator to weak head normal form, which is useful for many finite scalar summaries but is not deep evaluation of every nested field. A suitable foldr can produce a result without demanding the entire tail, allowing short-circuit behavior on some infinite lists. Choose based on both result semantics and demand.
import Data.List (foldl')
main = do
print (foldl' (+) 0 ([1..4] :: [Integer]))
print (foldr (||) False (True : repeat False))10 True
The strict left fold sums a finite list. The right fold can return True without evaluating its infinite tail.
Try it yourself
Compare left and right subtraction folds by writing their parenthesized expansions.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING