Funs: anonymous functions
| fun ... end | |
| Apply a fun | |
| Capture by name | |
| Closures |
fun ... end
The fun keyword starts an anonymous function, and end closes it. The arguments sit in parentheses, and the body follows the arrow.
A fun is a value like any other: bind it, pass it, or return it.
1> Double = fun(X) -> X * 2 end.
#Fun
2> Double(21).
42
Apply a fun
Call a fun directly with parentheses. The erlang:apply function does the same with the fun and its arguments as a list.
Direct calls are the everyday form; apply shows up when the argument list is built at runtime.
1> Add = fun(A, B) -> A + B end.
2> Add(2, 3).
5
3> erlang:apply(Add, [2, 3]).
5
Capture by name
The fun with a module, function, and arity captures an existing function without calling it. The result is a fun that calls that function.
This is the bridge between named functions and the higher-order tools of lesson 22.
1> Member = fun lists:member/2.
#Fun
2> Member(2, [1, 2, 3]).
true
Closures
A fun remembers the variables around it at the moment it was created. The captured values stay alive inside the fun, even after the outer function returns.
Closures keep state without mutation: the captured value is bound once, as ever.
1> make_adder(N) ->
fun(X) -> X + N end.
1> Add10 = make_adder(10).
2> Add10(5).
15
Next: Higher-order functions
Article author: Arthur Isaev