Named Anonymous Functions in Elixir

Does Elixir support anonymous features like 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 an anonymous function.

+4
source share
1 answer

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)
#=> 8

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
+6
source

Source: https://habr.com/ru/post/1680459/


All Articles