Ronaldo wrote
Unhappily there is no tips about tail recursion elimination on the manual.
May be some might be included in the section Tips & Tricks.
I haven't checked the OpenSCAD source, but tail recursion is simple to
understand: the last thing the function does must be to execute itself.
function sum_nF(n, max, tot=0) = n > max ? tot : sum_nF(n+1, max, tot+n);
is good because the last thing the function does is to call itself. If you
have
function sum_nR(n, max) = n > max ? 0 : sum_nR(n+1, max) + n;
or
function sum_nR(n, max) = n > max ? 0 : n + sum_nR(n+1, max);
Then the last thing the function does is add n to the result of the
function, even if you put "n+" first it can't be done until the function
call returns, and it cannot be optimised.
There are three sorts of recursive functions.
One calculates everything as the recursion winds up -- sumF above. It does
all the work on the forward path and the result is just passed straight back
from the last call.
The second rolls quickly forward and calculates the result as the recursion
unwinds -- sumR above. It does the work on the reverse path.
The third does different things in each direction. I have a nice function in
C that adds up memory requirements on the forward path and allocates the
memory on the reverse path.
Only the first of those can be optimised for tail recursion.
--
View this message in context: http://forum.openscad.org/another-beginner-question-syntax-for-a-sum-tp18467p18484.html
Sent from the OpenSCAD mailing list archive at Nabble.com.
Nice view, Urwin. But the issue is that not all tail recursion code is
entitled to recursion elimination in OpenSCAD. For instance, the following
is not because of the let():
function sum_nF(n, max, tot=0) =
let(ptot = tot+n)
n > max ?
tot :
sum_nF(n+1, max, ptot);
So it would be nice to have tail recursion elimination explained in the
manual.
--
View this message in context: http://forum.openscad.org/another-beginner-question-syntax-for-a-sum-tp18467p18485.html
Sent from the OpenSCAD mailing list archive at Nabble.com.