Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named anonymous functions in Elixir

Tags:

elixir

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.

like image 334
Mahmud Adam Avatar asked Jun 30 '17 02:06

Mahmud Adam


People also ask

Which function is called anonymous on named 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.

What is the difference between anonymous and named 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.

What is anonymous function with example?

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();

Can we assign an anonymous function?

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.


1 Answers

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
like image 177
Sheharyar Avatar answered Oct 08 '22 10:10

Sheharyar