home .. forth .. colorforth mail list archive ..

[ColorForth] Tail-recursion optimisation idea


A counted loop in colorForth can be done
     : foo ( n)   . . .  -1 + if  foo ;  then  drop ;
However, that requires 2 jumps.

So I reluctantly define  'begin'  and  'until'  so that
     : foo ( n-1)   begin . . .  -1 + until  drop ;
This uses only 1 jump.  'until'  is defined using  '-if' , jumping while
positive. Thus it includes the index value 0, terminates with -1 on the
stack and requires 'n-1' as the loop count.

A varient is
     : foo ( -1 n-1 --  -1)   begin . . . over + until  drop ;
if -1 happens to be on the stack.

The fastest loop for n < 32 is
     : foo ( m)   begin . . .  2* until  drop ;
where  m = 2**(31 - n). It shifts till the sign bit is set. So
     m = 1 loops 31 times
     . . .
     m = 40000000 loops once.
Of course, the allowable range is word-length dependent - not very portable.

------------------------

To Unsubscribe from this list, send mail to Mdaemon@xxxxxxxxxxxxxxxxxx with:
unsubscribe ColorForth
as the first and only line within the message body
Problems   -   List-Admin@xxxxxxxxxxxxxxxxxx
Main ColorForth site   -   http://www.colorforth.com