optimization of list comprehensions

Serge Aleynikov serge@REDACTED
Mon Mar 6 14:43:19 CET 2006

Thanks Robert, I indeed use lists:foldl/3 quite extensively.  However 
the idea is that if the parser supports list comprehensions, why not 
allowing for folding as a variation of the comprehension syntax, as this 
pattern is used as frequently as the basic list comprehension itself?

If we can represent:

   fun(I) -> I end,
     fun(N) ->
       N > 10
     lists:seq(1, 20)).

like this:

[I || I <- lists:seq(1, 20), I > 20].

Why not having a similar concise representation for the following case?

   fun(I, Acc) -> Acc+I end,
     fun(N) ->
       N > 10
     lists:seq(1, 20)).



Robert Virding wrote:
> lists:foldl/3 does what you want, you pass in accumulator which is 
> modified, passed along and finally returned. You also have lists:foldr/ 
> which traverses the list right-to-left, and mapfoldl/r which also 
> returns the mapped list.
> Robert
> Serge Aleynikov skrev:
>> I do want to throw a vote for Mats' suggestion on the alternative syntax:
>> (I || I <- List) -> ok
>> What I also find limiting is that it's not possible to have an 
>> accumulator when using list comprehension.  Perhaps something like 
>> this could also be considered (unless someone can suggest a better 
>> syntax):
>> [Acc+1, I || Acc, I <- List](0) -> Acc1
>>                              ^
>>                              |
>>                        Initial Acc's value
>> Serge
>> Robert Virding wrote:
>>> I have been thinking about this a bit and I wonder if the 
>>> constructing of the return list really causes any problems. 
>>> Space-wise it will only be as large as the size of the input list, so 
>>> I wouldn't worry.
>>> Robert
>>> Ulf Wiger (AL/EAB) skrev:
>>>> 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().
>>>> 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.
>>>> /Ulf W

More information about the erlang-questions mailing list