concept fold in category functional programming

appears as: fold, folds
Functional Programming in C++

This is an excerpt from Manning's book Functional Programming in C++.

An alternative way to look at folding is to alter your perception of the binary function f passed to the std::accumulate algorithm. If you consider it to be a normal left-associative binary operator such as + that you can write in the infix notation, then folding is equivalent to putting this operator between every element in the collection. In the example of summing the movie scores, it would be equivalent to writing all the scores, one after the other, and putting + between them (see figure 2.8). This would be evaluated from left to right, just like the fold performed by std::accumulate.

Functional Programming in Java: How functional techniques improve your Java programs

This is an excerpt from Manning's book Functional Programming in Java: How functional techniques improve your Java programs.

But you could go further. The reduce method is a particular case of a more general method that might produce a result of a different type than the elements of the list. For example, it could be applied to a list of characters to produce a String. You’d need to start from a given value (probably an empty string). In chapters 3 and 5, you’ll learn how to develop this method (called fold). Also note that the reduce method won’t work on an empty list. Think of a list of integers—if you want to compute the sum, you need to have an element to start with. If the list is empty, what should you return? Of course, you know that the result should be 0, but this only works for a sum. It doesn’t work for a product.

All these methods can be implemented using a fold, but such implementations have a major drawback: the time needed to compute the result is proportional to the length of the list. Imagine you have a list of about a million elements, and you want to check the length. Counting the elements may seem the only way to go (this is what the fold-based length method does). But if you were adding elements to the list until it reaches a million, you surely wouldn’t count the elements after adding each one.

Can you think of an implementation using a fold instead of explicit recursion?