liveBook · Manning

Foldable

As explained in Learn Haskell by Example

Foldable is a Haskell type class for data structures whose elements can be traversed and reduced by folding operations.

Foldable is a Haskell type class for structures whose elements can be traversed and reduced. Its minimal definition requires foldr; functions such as null, length, elem, sum, maximum, and minimum can then be derived. section 8.2.1

Folding becomes concrete through familiar structures and tasks:

  • A left fold reduces elements from left to right by updating an accumulator. section 8.2.1
  • A right fold associates the combining function from the right, although both folds evaluate elements from left to right. section 8.2.1
  • Foldable extends the idea beyond lists to structures such as binary trees. section 8.2.1

Candy trails and fold expressions

A candy trail demonstrates folding through collection tasks: selecting fruity candies or retaining only the last five. GHCi examples then show foldl and foldr building visibly different parenthesized expressions from the same numbers.

How Learn Haskell by Example covers it

How deep it goes
Defines fold directions, gives recursive implementations, and stops short of showing the binary-tree instance code.
Examples
Uses candy trails, fruity-candy collection, last-five collection, binary trees, and expression-building folds.
What it assumes
Builds from list traversal and recursive folds before generalizing the pattern to trees and other structures.
What you can do after
Build it from scratch by implementing fold-based helpers and a Foldable instance for a binary tree.
How it connects
Connects folding with lists, trees, Data.List, Data.Text, and reduction operations in Python, Java, and C++.

Also explained in

Compare how 2 books explain foldable →

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.