# optimization of list comprehensions

Mats Cronqvist <>
Fri Mar 3 10:33:32 CET 2006

```Per Gustafsson wrote:
> Hi Mats
>
> Do I understand your construction correctly if I describe it like this:
>
> A fold-expression have the following syntax:
>
> (expr(X1,..XN,Y1,...,YM) || PatX <- List, PatY <-- Acc0)
>
> Where X1,...,XN are variables from PatX and Y1,...,YN are variables from
> PatY, List is the list to fold over and Acc0 is the initial accumulator.

no, but i think yours is nicer :>

what i had in mind was to have a reserved variable '_' (scoped inside the
comprehension) that would hold the value of the expression. this to avoid
introducing the <-- operator. i wasn't very happy with it (to perl-y).

e.g. the (unfortunately non-existing) string:join/2 function;

string:join(["a","b","c"],"/") -> "a/b/c"

can be implemented like this;

string:join([Pref|Toks],Sep) ->
lists:foldl(fun(T,Acc) -> [Acc,Sep|T] end, Pref, Toks).

with my construction it would become
(['_',Sep|T] || T <- Toks, '_' <- Pref).

in yours it would be (right?);

([P,Sep|T] || T <- Toks, P <-- Pref).

[...]

> I feel that the issue with adding (too many) of these kinds of
> constructs are that they tend to make the language harder to read
> because it becomes difficult to see the difference between the different
> constructs that look quite similar.

yes, of course. but it seems to me that there are only two basic patterns
here; the map-like and the fold-like.
the Erlang Reference Manual says; "[List comprehensions] provide a succinct
notation for generating elements in a list."
I want a similarrly succinct notation for folding over a list. i realize i'm
not the right person to decide what the syntax should look like.

> Another issue is that it probably
> would be quite difficult to convince the parser to accept this.

i'll take your word for that. of course, from my ivory tower that's an
implementation detail :>

mats

```