19 Fold

List.fold_right folds in values of the list from the right to the left. You can think of this as "accumulating an answer"

Let's implement it ourselves:

List.fold_left does the opposite, it folds from the left. Let's implement it!

Mnemonic: The accumulator goes on the side of the list that the function is named.

Why do we bother having both a fold_left and a fold_right. Let's try addition:

They're both the same! But what about subtraction?

In general, if the answer isn't associative and commutative, fold left and fold right do different things.

In addition, fold_left is tail recursive; however, fold_right isn't. There's work to be done after the recursive call in fold_right.

If you want a tail recursive from the right, you can reverse the list, then fold_right. This requires traversing the list an extra time, but doesn't increase asymptotic complexity.