English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Fun is used to define anonymous functions in Erlang. The general syntax of anonymous functions is as follows:
F = fun(Arg1, Arg2, ... ArgN) -> ... End
Description
F −This is the variable name assigned to the anonymous function.
Arg1, Arg2, ... ArgN −These are the parameters passed to the anonymous function.
The following example shows how to use anonymous functions.
-> module(helloworld). -> export([start/ start() -> A = fun() -> io:fwrite("Hello") end, A().
The following points should be noted about the above program.
The anonymous function is assigned to the variable A.
Through the anonymous function A().
When we run the above program, we will get the following results.
"Hello"
Here is another example of an anonymous function, but this one uses parameters.
-> module(helloworld). -> export([start/ start() -> A = fun(X) -> io:fwrite("~p~n",[X]) end, A(5).
When we run the above program, we will get the following results.
5
Anonymous functions have the ability to access variables outside the scope of the anonymous function. Let's look at an example.-
-> module(helloworld). -> export([start/ start() -> B == 6, A = fun(X) -> io:fwrite("~p~n",[X]), io:fwrite("~p~n",[B]), end, A(5).
The following points should be noted about the above program.
Variable B is outside the scope of the anonymous function.
Anonymous functions can still access variables defined in the global scope.
When we run the above program, we will get the following results.
5 6
One of the most powerful aspects of higher-order functions is that you can define a function within a function. Let's look at an example of how to achieve this goal.
-> module(helloworld). -> export([start/ start() -> Adder = fun(X) -> fun(Y) -> io:fwrite("~p~n",[X + Y]) end end, A = Adder(6), A(10).
The following points should be noted about the above program.
The adder is a higher-order function defined as fun(X).
The adder function fun(X) refers to another function fun(Y).
When we run the above program, we will get the following results.
16