elixir fibonacci
To generate the Fibonacci sequence in Elixir, you can use recursion. Here's an example of how you can implement it:
def fibonacci(n) when n <= 0, do: []
def fibonacci(1), do: [0]
def fibonacci(2), do: [0, 1]
def fibonacci(n) do
fibonacci(n - 1) ++ [List.last(fibonacci(n - 1)) + List.last(List.delete_at(fibonacci(n - 1), -1))]
end
In this code, the fibonacci
function takes an integer n
as input and returns a list containing the Fibonacci sequence up to the n
th number. The function uses pattern matching to handle base cases where n
is less than or equal to 0, 1, or 2. For n
greater than 2, the function recursively calls itself to calculate the previous Fibonacci numbers and then appends the sum of the last two numbers to the list.
To use this function, you can call it with the desired n
value, like this:
fibonacci(5)
This will return [0, 1, 1, 2, 3]
, which is the Fibonacci sequence up to the 5th number.