Sujet : Re: exercise in double number arithmetic
De : krishna.myneni (at) *nospam* ccreweb.org (Krishna Myneni)
Groupes : comp.lang.forthDate : 15. Jul 2024, 02:15:10
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v71t6u$clc8$1@dont-email.me>
References : 1 2
User-Agent : Mozilla Thunderbird
On 7/14/24 16:43, Marc Olschok wrote:
On Sat, 06 Jul 2024 22:20:45 Krishna Myneni wrote:
...
How many different ways can you choose 42 distinct objects, 21 at a
time? This is "n choose k" or the binomial coefficent.
Yes, M*/ comes in handy for C(n,0) = 1 , C(n+1,k+1) = C(n,k)*n/k
42 21 binom d.
gives 538257874440
where
: binom ( n1 n2 -- nd ) \ n k --> C(n,k)
dup 0=
IF 2drop 1 s>d
ELSE 2dup 1- swap 1- swap binom 2swap m*/
THEN ;
Gforth SEE nicely replaced the original 'recurse' with 'binom' for
better readability.
THank you for the recursive version. It's nice to have both looping and recursive examples.
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.
: binom ... ;
: binom ... binom ... ;
In the later definition of BINOM Forth requires the call to BINOM be the earlier definition if it exists in the search order. If it does not exist in the search order, then I believe the standard would require an error to occur.
Code such as shown in your output of SEE cannot be compiled when no earlier definition of BINOM exists. For this reason, it is not helpful for SEE to replace RECURSE with the word name.
The SEE in kForth shows the following:
see binom
5631665B9710 DUP
5631665B9711 0=
5631665B9712 JZ $1D
5631665B971B 2DROP
5631665B971C #1
5631665B9725 S>D
5631665B9726 JMP $1A
5631665B972F 2DUP
5631665B9730 1-
5631665B9731 SWAP
5631665B9732 1-
5631665B9733 SWAP
5631665B9734 $5631665B9710
5631665B973D EXECUTE-BC
5631665B973E 2SWAP
5631665B973F M*/
5631665B9740 RET
ok
A slightly smarter SEE would replace the address and the EXECUTE-BC virtual machine instruction with RECURSE.
-- Krishna