Erlang Notes – Higher order functions

Here is the fifth 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.

Higher order functions

A higher order function is any function which does one or more of the following:

  • Takes one or more functions as its input
  • Returns a function as its output

Functions that take functions as an argument

We already saw some examples of this in the last section. Remember this code:

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]

In this code, lists:map takes a function as an argument and applies the function to each member of the passed in list. A map function is a very common example of this pattern. I would expect that its fairly fundamental to any language that allows functions to be passed around as first class entities.

Functions that return functions

Functions that return functions are somewhat less common, but they can be useful to help us write generic code that can be parameterized at runtime to do different things. Here’s some imaginary, untested, code to help get the point across:

1> % Imagine some readings of various types exist...
1>MakeReadingFinder = fun(Type) -> (fun(DateRange) -> readings:find(Type, Date) end end.
#Fun
2>BeforeBreakfastReadingFinder = MakeReadingFinder(before_breakfast).
#Fun
3>BeforeBreakfastReadingFinder(now()).
% Readings are magically returned!

Although the example isn’t perfectly clear (there’s a better one on pg. 45 of Programming Erlang) you can see that what we’re doing is using the ability to return a function as a way to fill in some of the returned functions parameters before we use it.

This allows us to parameterize the function, and is probably going to be ideal for implementing Factory patterns etc. very simply.

Leave a Comment