To understand what funs are all about, it is best to start with an example.
Type the following assignment clause in an Erlang shell, binding the
Bump to a fun:
Bump = fun(Int) -> Int + 1 end.
The fun takes a variable as an argument, binds it to the variable
Int, and “bumps up” its numerical value
by one. You call the fun by following it with its arguments in
parentheses, just as though you were calling a function. You can use its
name if it has been assigned to a variable:
Bump = fun(Int) -> Int + 1 end.#Fun<erl_eval.6.13229925> 2>
Or, you can call it directly:
fun(Int) -> Int + 1 end)(9).10
A fun is a function, but instead of uniquely identifying it with a module, function name, and arity, you identify it using the variable it is bound to, or its definition. In the following sections, we will explain why funs are so relevant and useful.
One of the most common operations on lists is to visit every element and transform it in some way. For instance, the following code compares functions to double all elements of a numeric list and to reverse every list in a list of lists:
doubleAll() -> revAll() -> ; ; doubleAll([X|Xs]) -> revAll([X|Xs]) -> [
X*2| doubleAll(Xs)]. [
Can you see a common pattern between the two functions? All that
differs in the two examples is the transformation affecting the element
X, italicized in the example; this can be captured by a function, giving the ...