Erlang Notes – Anonymous functions

Here is the fourth of some notes about erlang.
Obviously this is a very cursory glance at things. It’s really just notes to help me remember things. If you’re looking for something in more detail you can take a look at the erlang reference manual.

Anonymous functions

Anonymous functions in erlang are known as funs.

Funs work mostly like regular functions – they can take any number of arguments, the arguments can be of any type, and the function can have multiple clauses. The thing that makes anonymous functions useful is that they can be bound to a variable. For example:

1> Half = fun(X) -> X / 2 end.
#Fun
2> Half(3).
1.5

Or, with multiple clauses:

1> DistanceConvert = fun({miles, M}) -> {kilometers, 1.609344 * M};
1> ({kilometers, K}) -> {miles, 0.6213 * K}
1> end.
#Fun
2> DistanceConvert({miles, 10}).
{kilometers,16.09344}
3> DistanceConvert({kilometers, 15}).
{miles,9.3195}

Many other languages allow anonymous functions bound to variables. Think of Ruby or Python’s lambdas or, as an even closer analogy, of Javascript’s assignment of methods to variables.

Anonymous functions as arguments

Much like Javascript or Ruby, you can use these anonymous functions as arguments to other functions. This enables us to perform list wide operations using internal iterators, and to perform operations such as map and filter. For example:

1> List = [2,4,6,8,10].
[2,4,6,8,10]
2> Triple = fun(X) -> 3 * X end.
#Fun
3> lists:map(Triple, List).
[6,12,18,24,30]

As you can imagine, this opens up a lot of power. As far as I can tell the syntax for passing in funs allows you to pass them in as any parameter, and to call them inside a function clause body just by using the () call syntax.

It would also be interesting to know if funs are full closures. That is, do they keep their bindings with them when they’re passed around? As far as I know, I think they lose it, so they’re not.

Leave a Comment