optimization of list comprehensions

Ulf Wiger (AL/EAB) <>
Sun Feb 26 14:19:48 CET 2006


 
Samuel Rivas wrote:
>
> Ulf Wiger (AL/EAB) wrote:
>
> > 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.

Because 

  [ets:insert(T, {K,V}) || {K,V} <- L, 
                           17 > V, V > 144]

is decidedly more concise and readable than

  lists:foreach(fun({K,V}) when 17 > V, V > 144 ->
                      ets:insert(T, {K, V});
                   (_) -> ok
                end, L)

42 characters vs. 73, or seen another way:
7 characters of overhead vs 38.

I don't fault programmers for choosing the 
construct that's both easiest to write and 
read, even if it means building a list unnecessarily.

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

Indeed. A smart compiler would detect whether
the value from the list comprehension is used
in any way, which includes being used as the
return value from the enclosing function. (:

/Ulf W



More information about the erlang-questions mailing list