Tail recursions and reversing a list →
So, how about reversing a list using our leftee
function from our previous post?
Let’s work it out now. Here’s the original tail recursive function for your reference:
All you need to observe is how the accumulator acc
changes - here we take a list element we are currently processing and stick it before (at the head) of the current accumulator acc
.
In most functional programming languages our leftee
is actually called fold_left
and is tail recursive. There’s also a fold_right
which is not tail recursive, because of the way it applies the function to the list elements. More on this in a later post!