Erlang – Funs


Erlang – Funs


”;


Funs are used to define anonymous functions in Erlang. The general syntax of an anonymous function is given below −

Syntax

F = fun (Arg1, Arg2, ... ArgN) ->
   ...
End

Where

  • F − This is the variable name assigned to the anonymous function.

  • Arg1, Arg2, … ArgN − These are the arguments which are passed to the anonymous function.

The following example showcases how the anonymous function can be used.

Example

-module(helloworld). 
-export([start/0]). 

start() -> 
   A = fun() -> io:fwrite("Hello") end, 
   A().

The following things need to be noted about the above program.

  • The anonymous function is assigned to the variable A.

  • The anonymous function via the variable A().

When we run the above program we will get the following result.

“Hello”

Another example of anonymous function is as follows, but this is with the use of parameters.

-module(helloworld). 
-export([start/0]). 

start() -> 
   A = fun(X) -> 
      io:fwrite("~p~n",[X]) 
      end, 
   A(5).

When we run the above program we will get the following result.

Output

5

Using Variables

The Anonymous function have the ability to access the variables which are outside of the scope of the anonymous function. Let’s look at an example of this −

Example

-module(helloworld). 
-export([start/0]). 

start() -> 
   B = 6, 
   A = fun(X) -> 
      io:fwrite("~p~n",[X]), 
      io:fwrite("~p~n",[B]) 
      end, 
   A(5).

The following things need to be noted about the above program.

  • The variable B is outside of the scope of the anonymous function.

  • The anonymous function can still access the variable defined in the global scope.

When we run the above program we will get the following result.

Output

5
6

Functions within Functions

One of the other most powerful aspects of higher order functions, is that you can define a function within a function. Let’s see an example of how we can achieve this.

Example

-module(helloworld). 
-export([start/0]). 

start() -> 
   Adder = fun(X) -> fun(Y) -> io:fwrite("~p~n",[X + Y]) end end, 
   A = Adder(6), 
   A(10).

The following things need to be noted about the above program.

  • Adder is a higher order function defined as fun(X).

  • The Adder function fun(X) has a reference to another function fun(Y).

When we run the above program we will get the following result.

Output

16

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *