3 ms·
Elixir counter in a loop: defmodule LoopCounter do def go, do: go(0) defp go(n) do IO.puts("n is #{n}") :timer.sleep(1000)
by jdimov10 10y ago
Elixir counter in a loop:
defmodule LoopCounter do
def go, do: go(0)
defp go(n) do
IO.puts("n is #{n}")
:timer.sleep(1000)
go(n + 1)
end
end
Or you can use processes and message passing to maintain state. More examples at: http://dantswain.herokuapp.com/blog/2015/01/06/storing-state-in-elixir-with-processes/ http://dantswain.herokuapp.com/blog/2015/01/06/storing-state...
- firasd 10y agoInteresting. I was trying to do something like: tasks = for i <- urls do Task.start(fn -> :timer.sleep(5000 * the_counter) # more stuff end) end So each task would run 5 seconds after the previous one, etc. I definitely need a deeper understanding of the whole environment and language though. Will check out the article.
- tomku 10y agoHere's a couple ways of doing that, packaged as a runnable .exs script that you can mess around with: https://gist.github.com/tomku/21eab22e98950f31a072a2ac63900b16 https://gist.github.com/tomku/21eab22e98950f31a072a2ac63900b... The key ingredient is Enum.with_index, which pairs your enumerable with the indices that you'd have in an iterative 'for' loop in another language. I've also changed from Task.start to Task.async so that I can collect the tasks and wait for them at the end of the script. Edit: The recursive approach jdimov10 explained is really useful too, you'll see that pattern of using a recursive function's arguments to hold state all over the functional programming world.
- firasd 10y agoThanks for the code sample! Will give it a try.