Tail-Call Optimization

Every time we call a function, it consumes memory. Usually we don’t need to worry much about it—machines today have plenty of memory, and the Erlang VM does a great job keeping computation costs low for a decent amount of data. But when some input makes our function do millions of recursive calls, that consumes significant memory. In this section, we’ll discuss a way of creating recursive functions that have constant and low memory consumption. We’ll take advantage of compiler tail-call optimization.

Tail-call optimization is when the compiler reduces functions in memory without allocating more memory. It’s a common compiler feature in functional programming languages. To use it, we need to ensure that the last expression ...

Get Learn Functional Programming with Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.