Skip to content

Instantly share code, notes, and snippets.

@pulkit110

pulkit110/fix.ex Secret

Last active September 30, 2021 11:27
Show Gist options
  • Save pulkit110/e49fadea22e60758c26c5b6e81391ec1 to your computer and use it in GitHub Desktop.
Save pulkit110/e49fadea22e60758c26c5b6e81391ec1 to your computer and use it in GitHub Desktop.
Fibonacci Generator using a GenServer
defmodule Fib do
use GenServer
def init(_args), do: {:ok, %{0 => 0, 1 => 1}}
def handle_call(:get, _from, state), do: {:reply, state, state}
def handle_call({:get, number}, _from, state), do: {:reply, state[number], state}
def handle_cast({:compute, number}, state) do
last = Map.keys(state) |> Enum.max()
new_state =
(last + 1)..number
|> Enum.reduce(state, fn i, intermediate ->
Map.put(intermediate, i, intermediate[i - 1] + intermediate[i - 2])
end)
{:noreply, new_state}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment