O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required