I’d like to suggest an enhancement for the for
comprehension syntax. This is motivated by a feature of the Common Lisp loop
macro. I’m completely open to the particular syntax, but I’d like to hear what people think about the semantics. Here is an example.
for{
x <- xs
y = 1 then f(y)
z <- zs
}
The semantics are that the first time through the x
map*
loop, y
is bound to 1
, thereafter after x
is bound to its next value, y
is bound to f(y)
where y is the value from the previous iteration. E.g.,
for{
x <- xs
y = true then !y
z <- zs
}
In this example y is bound to true
, then false
, then true
, etc… Another example:
for{
x <- xs
y = 0 then (y+1) % 3
z <- zs
}
In this case y
iterates through the sequence 0, 1, 2, 0, 1, 2, etc…
Note that in each of these examples, there is only an x
loop and a z
loop. The y=...
syntax does not evoke another call to map/flatMap
, but rather a binding within the map/flatMap
of x
The same behavior can be achieved in an awkward way using foldLeft
, and I suggest more difficult to read:
xs.foldLeft((zero,0)){ ((acc,y), x) => {
(acc ++ zs.map(f(x,y,z)),f(y)) // ++ to emulate flatMap of x
}}
The conversation started here.
I welcome anyone’s comments.