liveBook · Manning

Right fold

As explained in Learn Haskell by Example

A right fold reduces a data structure by associating its accumulating function from the right.

A right fold reduces a list by recursively folding its tail before applying the combining function to the current element. Its list type is `(a -> b -> b) -> b -> [a] -> b`: the function receives an element and the accumulated result, while the base value handles the empty list. section 8.2.1

Building an expression from the right

Folding `[1..9]` with an initial value of `"0"` produces `"(1+(2+(3+(4+(5+(6+(7+(8+(9+0)))))))))"`. The parentheses make the right association visible: the last element combines with the base first, then each preceding element wraps that result. section 8.2.1

Listing 8.4 A right fold function on lists
foldRight :: (a -> b -> b) -> b -> [a] -> b
foldRight _ z [] = z                            #1
foldRight f z (x : xs) = f x $ foldRight f z xs     #2

Use this implementation to trace the empty-list case and the recursive step that applies `f` after folding the tail. section 8.2.1

Right folds also support broader data-structure abstractions:

  • `Foldable` provides `foldr` and derives convenience operations such as `null`, `length`, `elem`, `sum`, `maximum`, and `minimum` from it. section 8.2.1
  • Practice implementing those operations with `foldr`, then define `Foldable` for a binary tree and relate left and right folds to its structure. section 8.2.1

How Learn Haskell by Example covers it

How deep it goes
Defines the type and recursive implementation, then extends the idea to Foldable structures and binary trees.
Examples
Demonstrates right association by constructing a parenthesized addition expression from integers.
What you can do after
Build it from scratch by implementing right folds and Foldable-derived operations for lists and binary trees.
How it connects
Connects right folds with left folds, Foldable, lists, Text, and binary trees.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.