Skip to content

Instantly share code, notes, and snippets.

@erikvullings
Created August 9, 2017 14:35
Show Gist options
  • Save erikvullings/b4022a2fe49cdfa72a3f17ec5ffd8118 to your computer and use it in GitHub Desktop.
Save erikvullings/b4022a2fe49cdfa72a3f17ec5ffd8118 to your computer and use it in GitHub Desktop.
Fast Fibonacci implementation in Elixir
# Fast Fibonacci implementation (using a Map to cache previous results)
# This code comes from a mailing-list post by José Valim.
#
# Run iex
# $ iex
# > c("fib_agent.exs")
# > { :ok, agent } = FibAgent.start_link()
# > IO.puts FibAgent.fib(agent, 38)
defmodule FibAgent do
def start_link do
cache = Enum.into([ { 0, 0 }, { 1, 1 }], Map.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
{ val, cache } = do_fib(cache, n - 1)
result = val + cache[n - 2]
{ result, Map.put(cache, n, result)}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment