Funs are written with the syntax: app
F = fun (Arg1, Arg2, ... ArgN) -> ... end
This creates an anonymous function of N arguments and binds it to the variable F. this
If we have already written a function in the same module and wish to pass this function as an argument, we can use the following syntax: lua
F = fun FunctionName/Arity
With this form of function reference, the function which is referred to does not need to be exported from the module. spa
We can also refer to a function defined in a different module with the following syntax: code
F = {Module, FunctionName}
In this case, the function must be exported from the module in question. orm
The follow program illustrates the different ways of creating funs: it
-module(fun_test). -export([t1/0, t2/0, t3/0, t4/0, double/1]). -import(lists, [map/2]). t1() -> map(fun(X) -> 2 * X end, [1,2,3,4,5]). t2() -> map(fun double/1, [1,2,3,4,5]). t3() -> map({?MODULE, double}, [1,2,3,4,5]). double(X) -> X * 2.
We can evaluate the fun F with the syntax: io
F(Arg1, Arg2, ..., Argn)
To check whether a term is a fun, use the test is_function/1 in a guard. Example: function
f(F, Args) when is_function(F) -> apply(F, Args); f(N, _) when is_integer(N) -> N.
Funs are a distinct type. The BIFs erlang:fun_info/1,2 can be used to retrieve information about a fun, and the BIF erlang:fun_to_list/1 returns a textual representation of a fun. The check_process_code/2 BIF returns true if the process contains funs that depend on the old version of a module. form