5

Does Elixir support named anonymous functions similar to Clojure? For example, I want to do something like this:

fib_fun = fn fib n -> if n <= 1 do 1 else fib(n - 1) + fib(n - 2) end end

so that I can recursively call the anonymous function.

Mahmud Adam
  • 3,489
  • 8
  • 33
  • 54

1 Answers1

7

Elixir doesn't support recursion in anonymous functions, but you can implement it as a Y-Combinator with guard clauses like this:

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 call it like usual:

fib.(5)
#=> 8

So it's a better idea to just write it as a normal method inside a module (which would also look much more cleaner):

defmodule Fibonacci do
  def get(n) when n <= 1, do: 1
  def get(n), do: get(n-1) + get(n-2)
end
Sheharyar
  • 73,588
  • 21
  • 168
  • 215