Higher Order Function Question

Richard Carlsson <>
Mon May 27 16:05:39 CEST 2002


On Sat, 25 May 2002, Alex Peake wrote:

> I was struggling to use "filter" with the "complement of" a predicate (in my
> case not attr:isPk).
> 
> In explaining the problem, it came out that in my code I wrote things like:
> 
> lists:map({attr,varName}, rel:attrList(rel:findNamed(ng,"Member"))).
> 
> I was informed that this is "not elegant" and "inefficient" because it "is
> the old classic version of how to call a fun".

In the bad old days, there were no lambda closures at all in Erlang, and
this 2-tuple thing was added as a kind of simple poor man's lambda. But
things have improved since then, and the ability of 'apply' to interpret
2-tuples as function values is really something that is best forgotten.
Really.

> lists:map(fun(Arg) -> attr:varName(Arg) end,
> rel:attrList(rel:findNamed(ng,"Member"))).
> 
> is more efficient, but as programmer reading this, I find the
> fun...end part makes the intent less clear.

I'd claim the opposite, in fact. First, the "fun (...) -> ... end"
clearly shows what the operation to be passed to "map" is. Second, the
call "attr:varName(...)" makes it apparent that we are calling a certain
function (with a certain arity) in a certain module, and what the
arguments to that function will be. Of course it requires a few more
characters to type, but as a programming pattern it is both cleaner and
more powerful.

If the function was a local one (in the same module), you could write

	lists:map(fun varName/1, MyList)

but there is no notation "fun M:F/A" for functions in other modules,
because of the way inter-module ("remote") calls work with dynamic code
replacement in Erlang.

List comprehensions are of course very elegant, but only work for
operations that are combinations of map/filter.


Richard Carlsson ()   (This space intentionally left blank.)
E-mail: 	WWW: http://www.csd.uu.se/~richardc/
 "Having users is like optimization: the wise course is to delay it."
   -- Paul Graham





More information about the erlang-questions mailing list