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?