Funs

06/05/2009

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 -> http://erlang.org/doc/apps/stdlib/index.html

Now if we execute:

GoAwayIphone(ThingsIDesire).

we will obtain:

[mouse,keyboard]

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).

so

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!

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: