Agents—A Teaser

Our Fibonacci code is seriously inefficient. To calculate fib(5), we calculate this:

 
fib(5)
 
= fib(4) + fib(3)
 
= fib(3) + fib(2) + fib(2) + fib(1)
 
= fib(2) + fib(1) + fib(1) + fib(0) + fib(1) + fib(0) + fib(1)
 
= fib(1) + fib(0) + fib(1) + fib(1) + fib(0) + fib(1) + fib(0) + fib(1)

Look at all that duplication. If only we could cache the intermediate values.

As you know, Elixir modules are basically buckets of functions—they cannot hold state. But processes can hold state. And Elixir comes with a library module called Agent that makes it easy to wrap a process containing state in a nice module interface. Don’t worry about the details of the code that follows—we cover agents and tasks. For now, just see how processes are ...

Get Programming 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.