What are Anonymous Functions in Elixir?

Anonymous Functions

Anonymous functions have no name and are used to fulfil some functionality in the form of small code blocks. Generally, anonymous functions are the ultimate choice for small pieces of code or functions that have fewer calls.

Syntax

The building blocks of an anonymous function are fn, ->, and end.

The syntax for defining an anonymous function in Elixir is:

fn args -> command end

When calling the anonymous function, we write the assigned name, followed by ., and then any of the function’s parameters.

Example

The following is an anonymous function using an & operator in Elixir.

#An anonymous function using & operator
myAddition = fn (a, b) -> a + b end
#function called using assigned name
IO.puts (myAddition.(2, 3))

Explanation

As is evident from the example, fn and end mark the start and end of the function, respectively. All the arguments, if any, are stated between fn and ->.

Capture Operator &

Using the & operator is another way of creating anonymous functions in Elixir. In this case, the syntax of the anonymous function is also changed.

Example

Let's create an anonymous function in Elixir using the capture operator, &.

#An anonymous function
myAddition = & (&1 + &2)
#function called using assigned name
IO.puts (myAddition.(2, 3))

Explanation

&1 and &2 act as placeholders for values that are passed to this anonymous function. In the case where there are more parameters, we will increase these placeholders.

Multiple Bodies

An anonymous function can have multiple bodies. Instead of using switch or selection operators, the function call is matched to the correct body through pattern-matching. As a result, the body whose pattern first matches the arguments is run. In case of no match, the code throws an error.

Example

In the following example, we have an anonymous function with multiple bodies in Elixir.

demo_function = fn
{:ok, result} -> IO.puts (Enum.join(["Printing output:", result], " "))
{:error} -> IO.puts "An error has occurred!"
end
#Call anonymous functions with multiple bodies
#Following two calls will perfectly match to one of the bodies
my_var = 10
demo_function.({:ok, my_var})
demo_function.({:error})

Explanation

Here function call decides which body of the function to execute. In the case of multiple matches, the first match is selected for execution. If a function call has no match, there will be a compile-time error. For Example, a function call like this

demo_function.({:error, some_result})

would have given an error for the above-created anonymous function.

Copyright ©2024 Educative, Inc. All rights reserved