Implementing a counter, aka: how to keep state in a closure

The problem definition seems to assume mutable state so there’s a bit of a mismatch here. It’d be a bit like saying “In every language I want to learn I look at how to set register X0 to 1 and then increment it, how do I do that with JS?”. Javascript doesn’t manipulate registers, and Elixir doesn’t mutate values in closures.

Nonetheless, You can simulate mutable state with a process, and the Agent module provides a handy API in this case.

iex(6)> {:ok, pid} = Agent.start_link(fn -> 0  end)                     
{:ok, #PID<0.113.0>}
iex(7)> fun = fn -> Agent.get_and_update(pid, fn i -> {i, i + 1} end) end
#Function<20.127694169/0 in :erl_eval.expr/5>
iex(8)> fun.()                                                           
0
iex(9)> fun.()
1
iex(10)> fun.()
2
iex(11)> fun.()
3
iex(12)> fun.()
4

I’ll leave the code to make two counters as an exercise for the reader

5 Likes