Skip to content

Instantly share code, notes, and snippets.


pulkit110/fix.ex Secret

Last active September 30, 2021 11:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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])
{:noreply, new_state}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment