October 2014
Intermediate to advanced
280 pages
7h 20m
English
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 ...
Read now
Unlock full access