Travis

Travis

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

Completely new to Elixir, but have an issue I am trying to figure out:

When interviewing candidates for Javascript roles I usually have them do a simple technical question:
counter1 = getCounter(1);
counter2 = getCounter(17);
counter1(); //gives 1
counter1(); //gives 2
counter2(); //gives17
counter1(); //gives 3

And the challenge is “Implement the function getCounter”. For candidates who understand functions and closures this takes 4-6 lines and less than a minute, and is generally impossible for everyone else, so is a very efficient sort. For new languages, I try building a version of this to get a sense of how anonymous functions and closures work (or don’t) in the language. I have not been able to solve this for Elixr. It is functional, it has closures, you CAN return functions, so it seems this should not only work, but be trivial…

Javascript:
getCounter = function(initVal) {
i = initVal - 1 //Fix off by 1
return function() {
i = i +1;
return i;
}
}

Go:
func getCounter(initVal int) func() int {
i := initVal - 1
return func() int {
i += 1
return i
}
}

Note that you do NOT know beforehand how many times your anonymous counter might be called (or when), nor what start value you might get. I have seen recursion mentioned quite a bit, but that would require that you know how many times you want to call your counter when you start. What is the Elixir way to do this properly?

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

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

NobbZ

NobbZ

Due to the way elixir works, you have to return an updated closure as well on each call (untested):

def get_counter(i \\1) do
  fn -> {i, get_counter(i + 1)} end
end

Usage is roughly like this:

c = get_counter(17)
{v, c} = c.()
#=> {17, ...}
{v, c} = c.()
#=> {18, ...}
Nicd

Nicd

To expand a bit on the reason why you need to do it in a way that may not be intuitive for a first time functional programmer: Data in Elixir is immutable. Immutabililty means that once you have created a piece of data, it can’t be changed.

Trying to simply create an anonymous function that adds to a counter like this won’t work:

c = 0
f = fn -> c = c + 1; c end
IO.inspect(f.()) # 1
IO.inspect(f.()) # Still 1
IO.inspect(f.()) # Even still 1

That’s because the data in variable c is immutable. Inside the function the code can rebind the variable c to point to another piece of data, but the original c outside the function does not change. Even if you set c to point to a new value outside the function, it still would not affect any earlier usage of the variable. So the c that is bound to the context of the closure f is always 1 and will be.

So that is why you mainly have two avenues to solve this problem. Either you can create a new process (like the Agent suggested by benwilson512), or you can create a new function with the updated value on each call and use the updated function on the next call, like NobbZ suggested.

You might wonder how a process can hold state and update it if data is immutable. That’s because a process basically runs an infinitely recursing function that it gives the updated state to for the next iteration. So (very much simplified) a process looks like this:

def run_process(state) do
  receive do
    msg ->
      new_state = update_state(msg) # Do something based on the state and return the new state
      run_process(new_state) # Recurse with the new state, effectively updating the state of the process
  end
end

You can see there that no immutability guarantees are broken and still the state is updated.

Hope this helps and doesn’t confuse further. :sweat_smile:

amarraja

amarraja

The attached article is a great read about state in Elixir. Interestingly, the examples used are pretty much the same as yours.

http://dantswain.herokuapp.com/blog/2015/01/06/storing-state-in-elixir-with-processes/

Where Next?

Popular in Questions Top

pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New

We're in Beta

About us Mission Statement