Elixir does not support recursion in anonymous functions , but you can implement it as a Y-Combinator with watchdog sentences as follows:
fib = fn x ->
fun = fn
(n, _) when n <= 1 -> 1
(n, fun) -> fun.(n-1, fun) + fun.(n-2, fun)
end
fun.(x, fun)
end
and name it as usual:
fib.(5)
So itβs best to just write it like a regular method inside a module (which will also look much cleaner):
defmodule Fibonacci do
def get(n) when n <= 1, do: 1
def get(n), do: get(n-1) + get(n-2)
end
source
share