The fold Function
Explore the fold function to combine elements of lists, trees, and other data types into single outcomes. Understand fold_right and fold_left, and see how fold abstracts common computations like sum, product, any, and all. Discover fold applications on binary trees, options, and natural numbers to efficiently process recursive data structures.
We'll cover the following...
The fold function on lists
Often, we need to combine list elements into a single value.
For example, given a list, we might want to calculate the sum or the product of its elements. Such a computation pattern can be realized in the functional paradigm through a powerful function abstraction called fold.
Let’s define a function, sum_list, to calculate the sum of all numbers from a list of integers.
Next, let’s define another function, prod_list, to return the product of all numbers from a list.
The sum_list and prod_list functions follow the same computation pattern.
- In case of an empty list
[], return an initial value,0forsum_list, and1forprod_list. - For a
hd :: tllist, apply a binary functionftohd, and the result for recursively processedtl. The function is addition+forsum_list, and multiplication*forprod_list.
This computation pattern is precisely what fold_right captures. We’ll see in a minute why it is called fold_right. There is another fold version called fold_left, but we’ll cover it later.
let rec fold_right f init l = match l with
| [] -> init
| hd :: tl -> f hd (fold_right f init tl)
Here, f is the function used to combine the list elements, init is the initial value. The last argument l is the input list.
This function is called fold_right because the way it works is visually similar to how we fold clothes. In particular, we fold the list from right to ...