Passing Functions as Arguments

Learn how you can pass functions as a parameter in other functions.

We'll cover the following

Functions are just values, so we can pass them to other functions. We use this ability of passing functions around pretty much everywhere in Elixir code. Let’s look at an example:

iex> times_2 = fn n -> n * 2 end 
#Function<12.17052888 in :erl_eval.expr/5>

This is a simple function, which is doubling the given parameter n.

iex> apply = fn (fun, value) -> fun.(value) end 
#Function<12.17052888 in :erl_eval.expr/5>

Here, apply is a function that takes another function and a value. It returns the result of invoking that function with the value as an argument.

iex> apply.(times_2, 6)
12

Try the above code in the terminal below.

Get hands-on with 1400+ tech skills courses.