Created
March 13, 2012 01:27
-
-
Save kyanny/2026028 to your computer and use it in GitHub Desktop.
Elixir fibonacci #1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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
Uh oh!
There was an error while loading. Please reload this page.