Skip to content

Instantly share code, notes, and snippets.

@dhc02
Created September 19, 2018 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dhc02/d4bed7a4af8fbe1143a7c4606dddbc64 to your computer and use it in GitHub Desktop.
Save dhc02/d4bed7a4af8fbe1143a7c4606dddbc64 to your computer and use it in GitHub Desktop.
Fibonacci sequence in Elixir
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]
@dhc02
Copy link
Author

dhc02 commented Sep 19, 2018

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.

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