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.
In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.
Anonymous functions are never hoisted (loaded into memory at compilation). Named functions are hoisted (loaded into memory at compilation). When invoking an anonymous function, you can only call it after the declaration line. A name function can be invoked before declaration.
An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation. Normal function definition: function hello() { alert('Hello world'); } hello();
An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With