# [OpenSCAD] flattening mixed lists of lists

runsun runsun at gmail.com
Sun Apr 12 03:02:52 EDT 2015

A full flattening can be achieved with:
function flatten(a)=    [ for(x=a)       for(b=len(x)==undef? x:flatten(x)
)       b ];a=[ [[1,2],[2,3]], [[[1,2],[2,3]]] ];echo( flatten(a) );//ECHO:
[1, 2, 2, 3, 1, 2, 2, 3]
We can then add a len(x)==2 to return a list of pairs:
function flatten2(a)=    [ for(x=a)       for(b=(len(x)==undef)
|| (len(x)==2) ?x:flatten2(x)          )       b ];echo( flatten2(a)
);//ECHO: [[1, 2], [2, 3], [1, 2], [2, 3]]

Note both will fail if flattening a more general list (that might contain
strings). Adding a str(x)==x would help:
function flatten3(a)=    [ for(x=a)       for(b= (str(x)==x) ||
len(x)==undef? x:flatten3(x)         )       b ];b=[ ["abc",
["def","g"]],"h"];echo( flatten3(b) );//ECHO: ["abc", "def", "g", "h"]

-----
\$  Runsun Pan, PhD
\$ -- OpenScad_DocTest: doc and unit test ( Github , Thingiverse  )
\$ -- Linux Mint 17.1 Rebecca x64  + OpenSCAD 2015.03.15
\$ -- Linux Mint 17.1 Rebecca x64  + OpenSCAD 2015.04.01.nightly

--
View this message in context: http://forum.openscad.org/flattening-mixed-lists-of-lists-tp12316p12347.html
Sent from the OpenSCAD mailing list archive at Nabble.com.
-------------- next part --------------
An HTML attachment was scrubbed...