Last active
April 11, 2022 18:23
-
-
Save drincruz/7700681371eff71da8da706cf998dc85 to your computer and use it in GitHub Desktop.
What Fibonacci looks like 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 ElixirLab.Fibonacci do | |
# Recursive | |
def fib(0), do: 1 | |
def fib(1), do: 1 | |
def fib(n), do: fib(n-1) + fib(n-2) | |
# Iterative | |
def iter_fib(0), do: 1 | |
def iter_fib(1), do: 1 | |
def iter_fib(index) do | |
Enum.reduce(2..index, [1, 1], fn(_i, acc) -> | |
# Calculate the Fibonacci value | |
fib_val = | |
# Take the accumulator | |
acc | |
# Flatten the list since we're appending fib_val by a new list | |
|> List.flatten() | |
# Sum those values | |
|> Enum.sum() | |
[Enum.take(acc, -1), fib_val] | |
end) | |
# This is now the previous Fibonacci value and index's value, so just take the last value | |
|> List.last() | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I find that thinking of the sequence as a sequence, i.e., a list, helps simplify the logic while also lending itself to tail recursion to avoid performance issues:
Usage:
> find 7 [1, 1, 2, 3, 5, 8, 13]