Tree fold (source code)

= Tree fold
{title2=`foldTree :: (b -> a -> b -> b) -> b -> Tree a -> b`}

A <structural recursion> replacing the empty binary tree by a value and a nonempty node by a combining function on its two folded children and root label. The result type may itself be a <function type>, allowing a fold to construct a membership <predicate> or a <difference list> rather than traversing all branches for every subsequent query.

More generally, choose one operation for each <data constructor>. For a <leaf-labelled binary tree> represented by `One a | Two (Tree a) (Tree a)`, the <tree fold> instead has <type signature> `(a -> b) -> (b -> b -> b) -> Tree a -> b`: one operation handles the leaf label, and the other combines the two folded children. Replacing the operations by the original <data constructors> reconstructs the input, as <structural induction> proves.