我有以下(效率有点低)代码:
\ 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 ;
据我了解,RECURSE
和rand-n-bits
中的ones-rec
都应该是正确的尾调用。但是,当我要求Gforth做10 rand-n-bits
时,我会溢出返回堆栈。 Gforth没有优化正确的尾调用,或者我只是没有正确地执行此操作?