Search code examples
recursionerlangfold

Folds versus recursion in Erlang


According to Learn you some Erlang :

Pretty much any function you can think of that reduces lists to 1 element can be expressed as a fold. [...] This means fold is universal in the sense that you can implement pretty much any other recursive function on lists with a fold

My first thought when writing a function that takes a lists and reduces it to 1 element is to use recursion.

What are the guidelines that should help me decide whether to use recursion or a fold?

Is this a stylistic consideration or are there other factors as well (performance, readability, etc.)?


Solution

  • folds are usually both more readable (since everybody know what they do) and faster due to optimized implementations in the runtime (especially foldl which always should be tail recursive). It's worth noting that they are only a constant factor faster, not on another order, so it's usually premature optimization if you find yourself considering one over the other for performance reasons.

    Use standard recursion when you do fancy things, such as working on more than one element at a time, splitting into multiple processes and similar, and stick to higher-order functions (fold, map, ...) when they already do what you want.