Fold (higher-order Function) - Folds As Structural Transformations

Folds As Structural Transformations

Folds can be regarded as consistently replacing the structural components of a data structure with functions and values. Lists, for example, are built up in many languages from two primitives: any list is either an empty list, commonly called nil  (), or is constructed by prepending an element in front of another list, creating what is called a cons  node ( Cons(X1,Cons(X2,Cons(...(Cons(Xn,nil))))) ), resulting from application of a cons function, written down as (:) (colon) in Haskell. One can view a fold on lists say, as substituting  the nil at the end of the list with a specific value, and each cons with a specific other function. Hence, one gets a diagram which looks something like this:

There's another way to perform the structural transformation in a consistent manner, with the order of the two links of each node flipped when fed into the combining function:

These pictures illustrate right and left fold of a list visually. They also highlight the fact that foldr (:) is the identity function on lists (a shallow copy in Lisp parlance), as replacing cons with cons and nil with nil will not change the result. The left fold diagram suggests an easy way to reverse a list, foldl (flip (:)) . Note that the parameters to cons must be flipped, because the element to add is now the right hand parameter of the combining function. Another easy result to see from this vantage-point is to write the higher-order map function in terms of foldr, by composing the function to act on the elements with cons, as:

map f = foldr ((:) . f)

where the period (.) is an operator denoting function composition.

This way of looking at things provides a simple route to designing fold-like functions on other algebraic data structures, like various sorts of trees. One writes a function which recursively replaces the constructors of the datatype with provided functions, and any constant values of the type with provided values. Such a function is generally referred to as a catamorphism.

Read more about this topic:  Fold (higher-order Function)

Famous quotes containing the words folds and/or structural:

    Bunched upside down, they sleep in air.
    Their sharp ears, their sharp teeth, their quick sharp faces
    Are dull and slow and mild.
    All the bright day, as the mother sleeps,
    She folds her wings about her sleeping child.
    Randall Jarrell (1914–1965)

    The reader uses his eyes as well as or instead of his ears and is in every way encouraged to take a more abstract view of the language he sees. The written or printed sentence lends itself to structural analysis as the spoken does not because the reader’s eye can play back and forth over the words, giving him time to divide the sentence into visually appreciated parts and to reflect on the grammatical function.
    J. David Bolter (b. 1951)