I have the following (somewhat inefficient) code:
\ RNG support
VARIABLE seed
: rand ( -- random )
seed @
DUP 13 LSHIFT XOR
DUP 17 RSHIFT XOR
DUP 5 LSHIFT XOR
DUP seed ! ;
\ Checker for number of set bits
: clear-lsb ( u -- u )
DUP 1- AND ;
: under++ ( u x -- u++ x )
SWAP 1+ SWAP ;
: ones-rec ( c u -- c u | c )
?DUP ( c 0 | c u u )
0<> IF EXIT ( c | c u )
THEN under++ clear-lsb RECURSE ;
: ones-rec ( c u -- c u | c )
?DUP IF
under++ clear-lsb
RECURSE
THEN ;
: ones ( u -- n )
0 SWAP ones-rec ;
\ Makes a random number with n set bits
: rand-n-bits ( n -- random )
rand ( n random )
OVER SWAP ( n n random )
ones ( n n bits )
= ( n f )
IF EXIT
THEN RECURSE ;
By my understanding, both the RECURSE
s in rand-n-bits
and ones-rec
should be proper tail calls. However, when I ask Gforth to do 10 rand-n-bits
, I overflow the return stack. Does Gforth not optimize proper tail calls, or am I simply not doing this correctly?