Skip to content

Instantly share code, notes, and snippets.

@kyanny
Created March 13, 2012 01:27
Show Gist options
  • Save kyanny/2026028 to your computer and use it in GitHub Desktop.
Save kyanny/2026028 to your computer and use it in GitHub Desktop.
Elixir fibonacci #1
defmodule Fib do
def fib(0) do 0 end
def fib(1) do 1 end
def fib(n) do fib(n-1) + fib(n-2) end
end
IO.puts Fib.fib(10)
@nallwhy
Copy link

nallwhy commented Feb 25, 2025

I implemented it using a top-down approach while utilizing memoization to avoid redundant calculations.

defmodule Fib do
  def run(n) do
    {result, _} = do_run(n, %{})

    result
  end

  defp do_run(n, memo) when n in [1, 2] do
    result_with_memo(n, 1)
  end

  defp do_run(n, memo) do
    case memo[n] do
      nil ->
        {result1, memo} = do_run(n - 1, memo)
        {result2, memo} = do_run(n - 2, memo)

        result_with_memo(n, result1 + result2)

      result ->
        {result, memo}
    end
  end

  defp result_with_memo(n, result) do
    {result, memo |> Map.put(n, result)}
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment