On Wed, Apr 11, 2018 at 12:17:22PM +1200, Frank van der Hulst wrote:
> From the manual:
>
> // recursion - find the sum of the values in a vector (array) by calling itself
> // from the start (or s'th element) to the i'th element - remember
> elements are zero based
>
> function sumv(v,i,s=0) = (i==s ? v[i] : v[i] + sumv(v,i-1,s));
I'd write
function sumv(v,i,s=0) = (i<s ? 0 : v[i] + sumv(v,i-1,s));
this won't infinitely recurse and just return zero if you accidentally
reverse the arguments. (it'd make sense to think of it as taking
the sum of elements 5 to 8, and write sumv (vect, 5, 8); )
This also works better when you hit the corner case:
// Take the sum from n elements starting at s.
function sumve(v,s,n=0) = sumv (v, s+n-1, s);
Now the "n=0" case really SHOULD return a value...
Roger.
--
**
[hidden email] **
http://www.BitWizard.nl/ ** +31-15-2600998 **
** Delftechpark 26 2628 XH Delft, The Netherlands. KVK: 27239233 **
*-- BitWizard writes Linux device drivers for any device you may have! --*
The plan was simple, like my brother-in-law Phil. But unlike
Phil, this plan just might work.
_______________________________________________
OpenSCAD mailing list
[hidden email]
http://lists.openscad.org/mailman/listinfo/discuss_lists.openscad.org