Funs are called ‘anonymous functions’, let’s try to define one:

Sum = fun(X, Y) -> X+Y end.

This funs simply sums X and Y.

In erlang there are (and is possible to define) functions that accept a fun as parameter, this kind of functions are called “higher-order functions”.

Let’s define a list with our wishes:

ThingsIDesire = [iphone, mouse, keyboard].

Now we can define a fun that remove iphone from the list (we have already a phone and we can’t spend more for this kind of things!):

GoAwayIphone = fun(Devices) -> lists:delete(iphone, Devices) end.

Note: doing lists:delete we are using a function available in erlang’s standard lib, you can see more of it ->

Now if we execute:


we will obtain:


To use a fun inside another function is really simple, in the standard lib there is a function called lists:member(item, list) that returns true if <item> is in the <list>.
If we try:

lists:member(iphone, ThingsIDesire).

it returns true (because iphone is in ThingsIDesire), but if I pass GoAwayIphone(ThingsIDesire) as second argument like:

lists:member(iphone, GoAwayIphone(ThingsIDesire)).

I got false!

Is also possible for a function to return a fun, for example we can do:

DevicesToBlock = [iphone].
CheckPresenceOfBlockedDevices = fun(Devices) -> (fun(Device) -> lists:member(Device, Devices) end) end.

We defined fun(Devices) that returns fun(Device), now let’s define the function that actually check an item:

CheckIfThisIsABlockedDevice = CheckPresenceOfBlockedDevices(DevicesToBlock).


CheckIfThisIsABlockedDevice(iphone). returns true and
CheckIfThisIsABlockedDevice(mouse). returns false

The argument passed to CheckIfThisIsABlockedDevice is passed to fun(Device) that checks if the passed item is in the DevicesToBlock list.

By now it sounds quite confusing … but I can imagine some benefit of it!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: