jashkenas/coffee-script — Issue #1935: Parallel array comprehensions?
Author: jawj
Created: 2011-12-15 15:20:22+00:00
State: open

Hi all. I've recently found myself doing this sort of thing (e.g. with 3D coordinates):

xs = [1,2,3]
ys = [4,5,6]
xs = [7,8,9]

for x, i in xs
y = ys[i]
z = zs[i]
# do something with x, y and z

It occurred to me that this might be something the language could lend a hand with. Wouldn't it be clean and elegant to be able to just write:

for x, y, z in xs, ys, zs
# do something with x, y and z

?

The index feature could be kept -- it's just the (number-of-source-arrays + 1)th value, e.g.

for x, y, z, i in xs, ys, zs
# do something with x, y, z and i

I've forked the source and had a go at hacking this in as a proof-of-concept (possibly not the gentlest intro to CoffeeScript's innards -- "Welcome to the hairiest method in all of CoffeeScript")

I've got this:

alert(x, y, z, i) for x, y, z, i in [1, 2, 3], [4, 5, 6], [7, 8, 9]

compiling to this:

_ref = [1, 2, 3];
_ref2 = [4, 5, 6];
_ref3 = [7, 8, 9];
for (i = 0, _len = Math.max(_ref.length, _ref2.length, _ref3.length); i < _len; i++) {
x = _ref[i]; y = _ref2[i]; z = _ref3[i];
alert(x, y, z, i);
}

The tests all still appear to pass, but I do get 'Conflict in grammar' Jison errors, and my new code shouldn't go near production. I don't have a parallel suggestion for for ... of loops (though I think sensible behaviours probably exist).

Still -- anyone think this is a good idea? Have I missed some horrible issue?

Cheers,
George