Created
August 9, 2017 14:35
-
-
Save erikvullings/b4022a2fe49cdfa72a3f17ec5ffd8118 to your computer and use it in GitHub Desktop.
Fast Fibonacci implementation in Elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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