Travis

Travis

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?

Showing Posts 1 to 4

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

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/

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:

— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

jeffyzooom
Hi all, I’ve been working on RustyCSV, a CSV parser and encoder for Elixir backed by Rust NIFs. Version 0.4.0 is now available. The goa...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews