-
-
Save fishcakez/898570ebf370311df411 to your computer and use it in GitHub Desktop.
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
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 | |
case Dict.size(cache) do | |
size when size > n -> | |
{cache[n], cache} | |
size -> | |
do_fib(cache, cache[size-2], cache[size-1], size, n) | |
end | |
end | |
defp do_fib(cache, prev, cur, max, max) do | |
next = prev+cur | |
{next, Dict.put(cache, max, next)} | |
end | |
defp do_fib(cache, prev, cur, n, max) do | |
next = prev + cur | |
do_fib(Dict.put(cache, n, next), cur, next, n + 1, max) | |
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