2015-08-15

Elixir: Agent Fibonacci!

I got interested in Elixir when I had to help someone troubleshoot something called Hyperledger, and it seemed neat.  I've always wanted to try Erlang but had heard the statement "Erlang makes hard things easy, and easy things hard" so I had backed off.  (I assume it was the syntax...?)

Elixir seemed the best of both worlds so... let's take a look.

I'm now skimming through Dave Thomas's "Programming Elixir", and I found a pretty confusing example of using an Agent to maintain state (that's what Agent's do in Elixir) to compute a fibonacci number.  And it was, as I said, confusing.  Subjectively, this looks a *lot* cleaner to me:


# Fibonacci with an Agent

defmodule AgentFib do
  def sl do
    Agent.start_link(fn -> HashDict.new end, name: __MODULE__)
  end

  def get(0), do: 0
  def get(1), do: 1
  def get(n) do
    f = Agent.get(__MODULE__, &(HashDict.get(&1, n)))
    if f do
      f
    else
      f2 = get(n-2)
      f1 = get(n-1)

      Agent.update(__MODULE__, &(HashDict.put(&1, n, f1+f2)))
      f1+f2
    end
  end
end

AgentFib.sl
n = String.to_integer(hd(System.argv))
AgentFib.get(n) |> IO.inspect