optimization of list comprehensions

Samuel Rivas <>
Sun Feb 26 23:58:45 CET 2006


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

  I agree that lists:foreach construction is trifle ugly. But using
lists comprehension is a hack. Maybe we must think of another syntax
(nonlist-comprehension? :))

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

  You mean encouraging this kind of writing? :
  
  broadcast(Pids,M) -> [P ! M || P <- Pids], ok.

  Well, maybe ... I still think it is a misuse, but is indeed easier to
read, specially if we add predicates ...

  Regards
-- 
	Samuel



More information about the erlang-questions mailing list