openscad/openscad — pull request #775 by OskarLinde (2014-05-03 11:07:12+00:00)
Title: List comprehensions

This issue adds list comprehensions with a syntax [proposed by doug moung](http://forum.openscad.org/List-comprehensions-tt7644.html#a7649). It is also dependent on the let()-expression proposal (#774). The proposed syntax is:

[ list-definition expression ]

Where `list-definition` is a (more or less arbitrary) mix of the elements
* `for (i = sequence)` -- iteration
* `if (condition)` -- filtration
* `let (x = value)` -- local variable assignment

e.g.

[
for (i = [1:10000])
let (j = i*i)
if (j % 2 == 0)
j
]

There are a number of syntactical design choices, but the most notable one is that

[ for (i=[0:3], j=[0:3]) i==j?1:0 ] == [ for (i=[0:3]) for (j=[0:3]) i==j?1:0 ] == [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
compared to

[ for (i=[0:3]) [ for (j=[0:3]) i==j?1:0 ] ] == [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]

(Having multi-iterator for-loops result in multidimensional arrays would have been an option)

A few other examples

Map the array `arr` over the function `fun(x)`

[ for (v = arr) fun(v) ]

Filter the array `arr` over the condition `cond(x)`

[ for (v = arr) if (cond(v)) v ]

Flatten an array-of-arrays `arr` one level

[ for (s = arr) for(e = s) e ]