Created
June 8, 2020 14:49
-
-
Save evmorov/767fb35435daaf05a78ae285890f15da to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Cache do | |
def init do | |
{:ok, pid} = Agent.start_link(fn -> %{} end) | |
pid | |
end | |
def set(pid, n, value) do | |
pid |> Agent.get_and_update(fn state -> {state, Map.put(state, n, value)} end) | |
pid | |
end | |
def get(pid, n) do | |
pid |> Agent.get(& &1[n]) | |
end | |
def print_state(pid) do | |
pid |> Agent.get(& &1) | |
end | |
end | |
defmodule Fibonacci do | |
def find(n) do | |
Cache.init() | |
|> Cache.set(0, 0) | |
|> Cache.set(1, 1) | |
|> find(n) | |
end | |
defp find(cache, n) do | |
cache | |
|> Cache.get(n) | |
|> value_or_find(cache, n) | |
end | |
defp value_or_find(_no_value = nil, cache, n) do | |
value = find(cache, n - 1) + find(cache, n - 2) | |
cache |> Cache.set(n, value) | |
value | |
end | |
defp value_or_find(value, cache, n), do: value | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment