Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

9. More Data Types and High-Level Constructs > Funs and Higher-Order Functions

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.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint