Download V4N2 - Forth

Transcript
: DIVISION (dividend, divisor ---)
0 QUOTIENT !
ACCUMULATE
CR QUOTIENT IS QUOTIENT ?
.I9 REMAINDER IS ” . ;
Returning to “depth recursion,” that RETURNS in order
to branch, this next procedure draws a branching tree.
PENDOWN or PENUP determine whether the moving “turtle”
draws or not. BI-TREE includes two recursive calls, one for
each side of the “V.” The “Y-shaped” element spans two
levels. Comparing with IN&OUT above, this procedure
returns with the parameter still on the stack - for use on
the other branch. In stepping thru, trust that the
procedure-as-a-whole is transparent and ignore the
MYSELFs. In fact the Zen of reading or writing recursive
procedures is to be NOT distracted to other levels by the
MYSELF. Just be in this instance.
0 VARIABLE LEVEL
: BI-TREE (size --- size)
LEVEL @ 1 c IF RETURN THEN (stoprule)
PENDOWN DUP FORWARD
-1 LEVEL +!
45 LEFT
DUP 6 9 RANGERAND 11 *I (branchsiz)
MYSELF (size --- size)
90 RIGHT
MYSELF (size --- size)
DROP
(branchsiz)
45 LEFT
1 LEVEL +!
PENUP DUP BACKWARD ;
: SETUP.BI-TREE (size,level---) 2 ENUF?
LEVEL ! GRAPHINIT FULLSCREEN
PENUP 95 BACKWARD BI-TREE DROP ;
: CYCLEUNTIL (startsize ---)
DUP 5 <
IF 90 RIGHT 95 + FORWARD ARROWHEAD
RETURN THEN
(stop rule)
6 LEFT DUP FORWARD
.I’
1R > DROP MYSELF :
m
1.atice
the same form, a “stoprule” at the beginn..ig of
the procedure. R > DROP prevents useless build-up on the
return stack, allowing unbounded repetition. But if
CYCLEUNTIL were called from within another word, the R>
DROP first removes from the return stack the address of
the next action in the “calling word,” jumping over,
instead to the level that called the “calling word.” To avoid
this little inconvenience I propose to have the recursive
word push its own PFA on the return stack with a variant
of MYSELF called TAILMYSELF.
: TAILMYSELF (---)
LATEST PFA [COMPILE] LITERAL
COMPILE >R ; IMMEDIATE
I show its use here in a division-by-subtraction operation that ACCUMULATESthe quotient in a variable of the
same name. You don’t have to tell me that /MOD is available
to do the same thing at a saving of 30 seconds. Note the
recursive call is the last word in the procedure.
0 VARIABLE QUOTIENT
: ACCUMULATE (divdnd, divsr --- remndr)
2DUP <
IF DROP RETURN THEN
(stoprule)
1 QUOTIENT +!
2DUP - ROT DROP SWAP
TAILMYSELF (divdnd, divsr --- remndr)
’I
1
Continued on next page
FORTH Dimensions
25
Volume IV, No. 2