Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
@h4cc

This comment has been minimized.

Copy link

h4cc commented Mar 15, 2015

Thanks for this example! 🚀

@pmarreck

This comment has been minimized.

Copy link

pmarreck commented May 10, 2015

one issue with this version is that it is not tail-call-optimized

@ChristopheBelpaire

This comment has been minimized.

Copy link

ChristopheBelpaire commented Sep 1, 2015

This one is tail call optimized :)

defmodule Fib do
  def fib(a, _, 0 ) do a end

  def fib(a, b, n) do fib(b, a+b, n-1) end

end
IO.puts Fib.fib(1,1,6)
@ghost

This comment has been minimized.

Copy link

ghost commented Feb 15, 2016

defmodule Fib do
defp fib(0) do 0 end
defp fib(1) do 1 end
defp fib(n) when n>=0 do
fib(n-1) + fib(n-2)
end
def fibo(x) do
for n<-0..x-1 , do: fib(n)
end
end
Output:
iex(1)>Fib.fibo(4)
[0, 1, 1, 2]

@simonneutert

This comment has been minimized.

Copy link

simonneutert commented Mar 13, 2017

An idiomatic take on this topic :)

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)
@dhc02

This comment has been minimized.

Copy link

dhc02 commented Sep 19, 2018

Another approach that returns the entire sequence as a list.

defmodule Fibonacci do
  def find(nth) do
    list = [1, 1]
    fib(list, nth)
  end

  def fib(list, 2) do
    Enum.reverse(list)
  end

  def fib(list, n) do
    fib([hd(list) + hd(tl(list))] ++ list, n - 1)
  end
end

Usage:

> find 7
[1, 1, 2, 3, 5, 8, 13]
@kanmaniselvan

This comment has been minimized.

Copy link

kanmaniselvan commented May 14, 2019

A little optimization to @dhc02's approach, which removes ++ operation to list as it's less performant and uses pattern matching for finding the first two elements of the list.

defmodule Fibonacci do
  def find(nth) do
    list = [1, 1]
    fib(list, nth)
  end

  def fib(list, 2) do
    Enum.reverse(list)
  end

  def fib(list, n) do
    [first_elem, second_elem | _] = list
    fib([first_elem + second_elem | list], n - 1)
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.