Cover by Francesco Cesarini, Simon Thompson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Funs and Higher-Order Functions

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 variable 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:

1> Bump = fun(Int) -> Int + 1 end.
#Fun<erl_eval.6.13229925>
2> Bump(10).
11

Or, you can call it directly:

3> (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.

Functions As Arguments

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)].               [reverse(X) | revAll(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 ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required