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.
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.
The following is an anonymous function using an &
operator in Elixir.
#An anonymous function using & operatormyAddition = fn (a, b) -> a + b end#function called using assigned nameIO.puts (myAddition.(2, 3))
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 ->
.
&
Using the &
operator is another way of creating anonymous functions in Elixir. In this case, the syntax of the anonymous function is also changed.
Let's create an anonymous function in Elixir using the capture operator, &
.
#An anonymous functionmyAddition = & (&1 + &2)#function called using assigned nameIO.puts (myAddition.(2, 3))
&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.
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.
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 bodiesmy_var = 10demo_function.({:ok, my_var})demo_function.({:error})
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.