optimization of list comprehensions

Mats Cronqvist mats.cronqvist@REDACTED
Tue Mar 7 12:14:23 CET 2006

Richard A. O'Keefe wrote:
[many interesting observations deleted]

> It's up to the proponents of a new notation
> to provide other samples showing that the notation _would_ pay off.  And
> in fairness, I must admit that if such a notation did exist, code might
> be written differently to take more advantage of it.  But that's just
> speculation.


   in the olden days, you saw lots of code like this;

goo(X) -> lists:reverse(goo(X,[])).
goo([],A) -> A;
goo([H|T],A) when is_integer(H) -> goo(T,[H|A]);
goo([_|T],A) -> goo(T,A).

   which most sane people would now write like this;

goo(X) -> [I || I <- X,is_integer(I)].

   interestingly, one almost never saw this (or variations thereof);

goo(X) -> lists:flatmap(fun(I) when is_integer(I)->[I];(_)->[] end, X).

   similarly, this;

foo(Xs) -> foo(Xs,root).
foo([],A) -> A;
foo([X|T],A) when is_atom(X) -> foo(T,{A,X});
foo([_|T],A) -> foo(T,A).

   would look a lot better like this (using Per Gustafsson's syntax;

foo(Xs) ->
     ({A,X} || X<-Xs, A<--root, is_atom(X)).

   i reject the argument "there is noo need for new syntax since one can already 
do this";

foo(Xs) ->
     lists:foldl(fun(X,A) when is_atom(X) -> {A,X}; (_,A) -> A end, root,Xs).

   firstly; it is actually a lot more difficult to read (although the LOC is the 
   secondly; for whatever reason normal industry programmers(*) will rarely if 
ever use lists:fold* (or indeed anything that involves funs). they didn't use 
lists:map or lists:foreach either, but they do use list comprehensions.

* by definition, anyone who writes erlang for a living and doesn't read this.


More information about the erlang-questions mailing list