Passing Functions As Arguments

Functions are just values, so we can pass them to other functions.

 iex>​ times_2 = ​fn​ n -> n * 2 ​end
 #Function<12.17052888 in :erl_eval.expr/5>
 iex>​ apply = ​fn​ (fun, value) -> fun.(value) ​end
 #Function<12.17052888 in :erl_eval.expr/5>
 iex>​ apply.(times_2, 6)
 12

In this example, apply is a function that takes a second function and a value. It returns the result of invoking that second function with the value as an argument.

We use the ability to pass functions around pretty much everywhere in Elixir code. For example, the built-in Enum module has a function called map. It takes two arguments: a collection and a function. It returns a list that is the result of applying that function to each element ...

Get Programming Elixir 1.2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.