Let’s start with the non-tail recursive version of map (the List module version is not tail recursive neither), the idea is to return a list 'b which is the result of applying the function 'a -> 'b to all the members of a list 'a, or well in our case ('a -> 'b) -> 'a seq -> 'b seq

Again, the original map function in the Caml standard list module is not tail recursive (the version in Core is), notice as well the use of the named arguments, when working with the mix of list and functions is a good idea to use them.

Let’s work in our tail recursive version, it will become easy if we use the now familiar reverse inner loop accumulator style

The power of fold

The fold operations are called reducers and aggregators by others, the idea is calculating a running value through a sequence. We agregate values from a sequence with a function who takes the current value and previous value of the applied function. In some parlance it is called reducers.

There are two versions of fold, the common left version folding from left to right (moving the apply function from the left to the right)

Let’s start with probably the most powerful function in the List module, fold_left

Next time (I hope) we will talk more about tail recursion and why some functions in the Caml standard library are not tail recursive (and core offers both versions). As usual the Jupyter notebook with more of my notes (and the origin of this series) is in my GitHub repo.