Created
August 14, 2014 18:32
-
-
Save stevedowney/2f910bd3d72678b4cf99 to your computer and use it in GitHub Desktop.
Fibonacci number calculator in Elixir.
This file contains 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 | |
# Naive implementation | |
def fib(0), do: 0 | |
def fib(1), do: 1 | |
def fib(n) | |
when is_integer(n) and n > 1, | |
do: fib(n-1) + fib(n-2) | |
def fib(_), do: {:error, "positive integers only"} | |
# Tail recursion version inspired by: http://stackoverflow.com/a/14294705 | |
# Not only can it take advantage of TCO, it also memoizes. | |
def fib_tr(0), do: 0 | |
def fib_tr(n) | |
when is_number(n) and n > 0, | |
do: fib_tr(n, 1, 0, 1) | |
def fib_tr(_), do: {:error, "positive integers only"} | |
def fib_tr(n, m, _prev_fib, current_fib) | |
when n == m, | |
do: current_fib | |
def fib_tr(n, m, prev_fib, current_fib), | |
do: fib_tr(n, m+1, current_fib, prev_fib + current_fib) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cash me outside howbow dah? 😄