Skip to content

Instantly share code, notes, and snippets.

@styx
Forked from josevalim/fib_with_agents.exs
Created May 19, 2014 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save styx/e821530b7e264344ef0d to your computer and use it in GitHub Desktop.
Save styx/e821530b7e264344ef0d to your computer and use it in GitHub Desktop.
defmodule FibAgent do
def start_link do
cache = Enum.into([{0, 0}, {1, 1}], HashDict.new)
Agent.start_link(fn -> cache end)
end
def fib(pid, n) when n >= 0 do
Agent.get_and_update(pid, &do_fib(&1, n))
end
defp do_fib(cache, n) do
if cached = cache[n] do
{cached, cache}
else
{val1, cache} = do_fib(cache, n - 1)
{val2, cache} = do_fib(cache, n - 2)
{val1 + val2, Dict.put(cache, n, val1 + val2)}
end
end
end
{:ok, agent} = FibAgent.start_link()
IO.puts FibAgent.fib(agent, 20)
IO.puts FibAgent.fib(agent, 20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment