Sujet : Re: exercise in double number arithmetic
De : nobody (at) *nospam* nowhere.invalid (Marc Olschok)
Groupes : comp.lang.forthDate : 31. Jul 2024, 22:59:09
Autres entêtes
Message-ID : <v8ec3d$k9gv$1@solani.org>
References : 1 2 3
User-Agent : tin/2.4.4-20191224 ("Millburn") (Linux/2.6.33.4 (i686))
On Mon, 15 Jul 2024 03:15:10 Krishna Myneni wrote:
[...]
THank you for the recursive version. It's nice to have both looping and
recursive examples.
On second thought it might be nicer to make it tail-recursive.
This way one can see the comparison with the equivalent loop.
Of course one needs to accumulate the intermediate products in
ascending order to preserve integrality.
\ d , k , n-k , n --> d*(n+1)/(k+1) , k+1 , n-k+1 , n
: mstep ( d n1 n2 n3 -- d n1 n2 n3 )
>r 1+ swap 1+ 2dup >r >r m*/ r> r> swap r> ;
\ d , 0 , n-k , n --> d*C(n,k) , k , n , n
: binom2_rec ( d n1 n2 -- d n1 n2 ) recursive
2dup < if mstep binom2_rec then ;
\ d , 0 , n-k , n --> d*C(n,k) , k , n , n
: binom2_loop ( d n1 n2 -- d n1 n2 )
2dup swap - 0 ?do mstep loop ;
: binom2 binom2_rec ;
\ n , k --> C(n,k)
: binom ( n1 n2 -- n )
>r >r 1 s>d 0 r> dup r> - swap binom2 2drop drop ;
There's a reason why RECURSE (or equivalent) is preferable to having the
name of the word in the output of SEE in Forth. This is because it is
possible to have an earlier definition with the same name and to call it
from within the definition e.g.
I remember this feature from long ago (I think it was mentioned in
'Starting Forth'), but it seems that since the edit/compile/run cycle
became so fast I had never used it.
-- M.O.