HASKELL / CHAPTER 06

List transformations and laziness

Advanced

Compose list operations and reason about how much input is demanded.

By the end of this chapter

  • Combine map and filter
  • Use folds with a suitable identity
  • Bound demand on an infinite list

The idea

Enter with lists, functions, and recursion understood. map transforms every demanded element, while filter retains elements satisfying a predicate. These operations describe common list processing without writing the traversal each time. A fold combines elements into another result using a combining function and a base value. Check the combination’s argument order instead of assuming every fold behaves identically.

Haskell is non-strict: expressions are evaluated as their results are needed. An infinite list can be useful when a consumer requests only a finite prefix. take 4 can bound demand, while trying to print or sum the entire infinite list never finishes normally. Laziness is not a promise that every pipeline is efficient; a filter searching for a nonexistent future match can still fail to produce another element.

Haskell example
main :: IO ()
main = print (take 4 (map (*3) [1..]))
Result
[3,6,9,12]

Only the first four mapped results are required. The infinite source does not need to be constructed in its entirety.

Try it yourself

Compose filter odd and map (*2) over a finite list, then predict the resulting order.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which expression can produce a finite result from the infinite list [1..]?