Returning a Function
Explore how to define functions in Elixir that return other functions, allowing nested anonymous functions to carry variables from their defining environment. Understand closures through hands-on examples of parameterized functions and scope retention.
We'll cover the following...
We'll cover the following...
In Elixir, functions are first-class citizens. We can define a function, assign it to a variable, and then use that variable to invoke the function. We can also pass a function as an argument to another function. This is often referred to as anonymous functions or lambdas in other programming languages.
An Elixir function can also return a function. Let’s elaborate on it through an example.
Here’s the code:
iex> fun1 = fn -> fn -> "Hello" end end
#Function<12.17052888 in :erl_eval.expr/5>
iex> fun1.()
#Function<12.17052888 in :erl_eval.expr/5>
iex> fun1.().()
"Hello"
The first line is hard to read, so let’s spread it out.
fun1 = fn ->
...