![]()
ello!
I’m trying to learn some Elixir by doing some exercises. Currently, I’m trying to understand how to write the equivalent of a fibonacci with a cache. At the moment, I came up with the following implementation:
defmodule M do
@moduledoc false
def main do
cache = spawn(M, :fib_cache, [%{}])
IO.puts(fib(10, cache))
end
def fib(n, cache_pid) do
case n do
1 -> 0
2 -> 1
3 -> 1
_ ->
send(cache_pid, {self(), :fetch, n})
receive do
{:reply, value} ->
if value != nil do
value
end
end
num = fib(n-1, cache_pid) + fib(n - 2, cache_pid)
send(cache_pid, {self(), :store, n, num})
receive do
{:ok} ->
num
end
end
end
def fib_cache(state) do
receive do
{from, :store, n, m} ->
IO.inspect(state)
send(from, {:ok})
fib_cache(Map.put(state, n, m))
{from, :fetch, n} ->
send(from, {:reply, Map.get(state, n, nil)})
fib_cache(state)
end
end
end
What is worrying me is the log that it prints when I run it:
iex(3)> M.main
%{}
%{4 => 2}
%{4 => 2, 5 => 3}
%{4 => 2, 5 => 3}
%{4 => 2, 5 => 3, 6 => 5}
%{4 => 2, 5 => 3, 6 => 5}
%{4 => 2, 5 => 3, 6 => 5}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13, 9 => 21}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13, 9 => 21}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13, 9 => 21}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13, 9 => 21}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13, 9 => 21}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13, 9 => 21}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13, 9 => 21}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13, 9 => 21}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13, 9 => 21}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13, 9 => 21}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13, 9 => 21}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13, 9 => 21}
%{4 => 2, 5 => 3, 6 => 5, 7 => 8, 8 => 13, 9 => 21}
34
:ok
In short, the state gets printed multiple times when in a equivalent implementation in a procedural language it would print once. My question is: what am I missing here? Are the functions executed in parallel when I create the num variable? Shouldn’t it fill the state with all the values from 1 to 10 and fib(n-2) be a O(1) operation?
Looking forward to hearing from you






















