Hasty Briefsbeta

Bilingual

Differences Between `Foldl` and `Foldr`

2 days ago
  • Both foldl and foldr traverse lists left to right; the difference is associativity (left vs right grouping).
  • In strict languages, foldl is tail-recursive and uses constant space; foldr requires linear stack space.
  • In lazy languages (like Haskell), foldl builds large thunks, so use foldl' for strict functions for constant space.
  • foldr can be lazy: if the combining function is lazy in its second argument, it can work incrementally and on infinite lists.
  • General rule for lists: use foldl' for strict operations, foldr for lazy second argument; avoid plain foldl or foldr'.
  • These rules are specific to lists; other data structures may require different choices (e.g., snoc lists).