Skip to content

Instantly share code, notes, and snippets.

@aleury
Created June 6, 2019 05:35
Show Gist options
  • Save aleury/89292560d9ca75d6aadd15ea1cfb0799 to your computer and use it in GitHub Desktop.
Save aleury/89292560d9ca75d6aadd15ea1cfb0799 to your computer and use it in GitHub Desktop.
Elixir Cached Fibonacci Sequence
defmodule Cache do
def run(body) do
{:ok, pid} = Agent.start_link(fn -> %{0 => 0, 1 => 1} end)
result = body.(pid)
Agent.stop(pid)
result
end
def get_or_put(cache, key, if_not_found) do
Agent.get(cache, fn map -> map[key] end)
|> put_if_not_found(cache, key, if_not_found)
end
defp put_if_not_found(nil, cache, key, if_not_found) do
value = if_not_found.()
Agent.get_and_update(cache, fn map ->
{value, Map.put(map, key, value)}
end)
end
defp put_if_not_found(value, _cache, _key, _if_not_found) do
value
end
end
defmodule CachedFib do
def fib(n) do
Cache.run(fn cache ->
cached_fib(n, cache)
end)
end
defp cached_fib(n, cache) do
Cache.get_or_put(cache, n, fn ->
cached_fib(n - 1, cache) + cached_fib(n - 2, cache)
end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment