Skip to content

Instantly share code, notes, and snippets.

@stevedowney
Created August 14, 2014 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevedowney/2f910bd3d72678b4cf99 to your computer and use it in GitHub Desktop.
Save stevedowney/2f910bd3d72678b4cf99 to your computer and use it in GitHub Desktop.
Fibonacci number calculator in Elixir.
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
@simonneutert
Copy link

simonneutert commented Mar 13, 2017

defmodule Fib do
    def fib(a, b, n) do
        case n do
            0 ->
                a
            _ ->
                fib(b, a+b, n-1)
        end
    end
end
# Console Output
IO.puts Fib.fib(1,1,7)

Cash me outside howbow dah? 😄

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