Trying to write a Cache module to calculate fibonacci numbers but getting: CompileError: undefined function error (passed parameter)

Hi everyone, I’m learning elixir and trying to write a Cache module to calculate fibonacci numbers.
When I compile the following module:

defmodule Cache do
  def start() do
    Agent.start_link(fn -> %{0 => 0, 1 => 1} end)
  end

  def get_specific_fib(n, {:ok, pid}) do
    Agent.get(pid, fn state -> state[n] end)
  end

  def update_cache(key, value, {:ok, pid}) do
    Agent.update(pid, fn state -> Map.put(state, key, value) end)
  end

  def in_map?(n, pid) do
    Agent.get(pid, fn state -> state[n] end)
  end

  def get_fib(n, pid_tuple) do
    fib(n, in_map?(n, pid_tuple), pid_tuple)
  end

  def fib(n, in_map=true, {:ok, pid}) do
    get_specific_fib(n, {:ok, pid})
  end

  def fib(n, in_map=nil, {:ok, pid}) do
    fib = Cache.get_fib(n - 1, {:ok, pid}) + Cache.get_fib(n -2, {:ok, pid})
    update_cache(key=n, value=fib, {:ok, pid})
    fib
  end
end

I get the following error:

** (CompileError) lib/cache.ex:31: undefined function n/2
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:677: :erl_eval.do_apply/6

line 31 is the following: fib = Cache.get_fib(n - 1, {:ok, pid}) + Cache.get_fib(n -2, {:ok, pid})

I’ve googled this and haven’t found an answer, thank you.

You have get_fib(n -2, {:ok, pid}), the parser sees this as get_fib(n(-2, {:ok, pid})) because of the optional parenthesis and fixity of the unary - is higher than the binary one. If you put a space between - and 2, it should work.

2 Likes

Thank you, I didn’t know this.