[OpenSCAD] feedback on "C-style for"

doug moen doug at moens.org
Wed Jun 1 16:07:56 EDT 2016


I've been playing with "C-style for" (which is an experimental feature in
the dev build).

It gets a bit cumbersome for complex examples with multiple loop variables,
so I'd like to suggest an improvement.

What I'd like is a parallel, pattern matching assignment statement. For
example,

[x,y,z] = point;

requires 'point' to be a list with exactly 3 elements (otherwise an error
is reported). The 3 elements are assigned to x, y and z. This would be
really handy for updating multiple loop variables in the update step.

First example is the fibonacci sequence.

function fibonacci(n) =
[
  for (a=0, b=1; b <= n; t=a, a=b, b=a+t) b
];
echo(fibonacci(10)); // [1, 1, 2, 3, 5, 8]

I'd like to get rid of the temporary variable 't', which I need because I
can't do a parallel assignment of a and b in the update step.

function fibonacci2(n) =
[
  for (a=0, b=1; b <= n; [a,b]=[b, b=a+b]) b
];

Second example is prime factors.

function prime_factors(n) =
[
  for (n=n, f=2;
       n>1;
       n1 = n%f==0 ? n/f : n,
       f = n%f==0 ? f : f+1,
       n = n1)
    if (n%f==0) f
];
echo(prime_factors(20)); // [2,2,5]

There are two things I'd like to fix here: the extra variable n1, and the
need to duplicate the 'n%f==0 ? ... : ...' logic for updating n and f.

function prime_factors2(n) =
[
  for (n=n, f=2;
       n>1;
       [n,f] = n%f==0 ? [n/f,f] : [n,f+1])
    if (n%f==0) f
];

As you can see, with this change the code becomes a lot shorter.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.openscad.org/pipermail/discuss_lists.openscad.org/attachments/20160601/b0261ae9/attachment-0002.html>


More information about the Discuss mailing list