Created
September 19, 2018 18:11
-
-
Save dhc02/d4bed7a4af8fbe1143a7c4606dddbc64 to your computer and use it in GitHub Desktop.
Fibonacci sequence in Elixir
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 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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you construct the Fibonacci sequence as a list, and construct it in reverse, Elixir's built-in head and tail functions make it easy to compute with tail-call optimization for free.