Combining all elements of a list using fold

In functional programming, a fold is a technique to reduce a data structure into a single value. There are two types of fold--left fold (foldl) and right fold (foldr). Let's suppose we have a list that contains 0, 1, 2, 3, and 4. Let's use the fold technique to add all the contents of the list, first using foldl and then foldr. However, there is a significant difference between the two--foldl is the left associative, which means we combine the leftmost element then move towards the rightmost element. For instance, by the list we have, we will get the following parentheses:

    ((((0 + 1) + 2) + 3) + 4)

While foldr is the right associative, which means we will combine the rightmost element then move ...

Get Learning C++ Functional Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.