optimization of list comprehensions

Samuel Rivas samuel@REDACTED
Sun Feb 26 13:25:48 CET 2006


Ulf Wiger (AL/EAB) wrote:
> I've seen many examples of how people use
> list comprehensions as a form of beautified
> lists:foreach() - that is, they don't care
> about the return value of the comprehension.
> 
> I hesitate to say that it's bad practice,
> even though one will build a potentially
> large list unnecessarily, since it's 
> actually looks a lot nicer than using 
> lists:foreach().

  Why? List comprehension is a tool to construct lists, lists:foreach
has different semantics.
 
> Question: would it be in some way hideous
> to introduce an optimization where such
> list comprehensions do everything except
> actually build the list? Then they could
> execute in constant space.
  
  I think it would. You would be writing a list that is not a list.

  A bit of elaboration:

  If you write [f(X) || X <- Somewhere] you mean "build a list applying f
to every member of <put here the constructors and conditions>".

  If you write lists:foreach(F,L) you mean "apply F to every member of L
just for the side effects, don't care about the result".

  On the other hand, a smart compiler may be able to avoid building the
list if it is not going to be used. But if the function were exported and
the list comprehension were its result the compiler would not be able to
apply the optimization anyway. So even if the optimization were
introduced it would not always work.

  Regards
-- 
	Samuel



More information about the erlang-questions mailing list