home *** CD-ROM | disk | FTP | other *** search
- \ Personal Stacks.
- \ ----------------
- \ In order to understand Forth's data stack a little better we are going
- \ to create our own personal stack. You see Forth's data stack is little
- \ more than an array with a word set for manipulating its elements.
-
- \ Create an array to be used for a 10 number stack.
- CREATE P-STACK 20 ALLOT \ Stack will hold 10 16bit numbers.
-
- VARIABLE P-INDEX \ Holds the value of user stack pointer.
-
- \ Clear and initialize the Personal user stack.
- : P-CLEAR ( -- D) ( ?? -- P)
- 0 P-INDEX ! P-STACK 20 ERASE ;
-
- \ Return number of elements on the user stack to Forth's data stack.
- : P-DEPTH ( -- n D)
- P-INDEX @ 2/ ;
-
- \ Increment user stack pointer with error checking.
- : P-INC ( -- D)
- P-INDEX @ 20 =
- IF ." P-OVERFLOW" P-CLEAR
- ELSE 2 P-INDEX +! THEN ;
-
- \ Decrement user stack pointer with error checking.
- : P-DEC ( -- D)
- P-INDEX @ 0=
- IF ." P-UNDERFLOW"
- ELSE -2 P-INDEX +! THEN ;
-
- \ Move number from Forth's data stack to the P-stack.
- : >P ( n -- D) ( -- n P)
- P-INC P-INDEX @ P-STACK + ! ;
-
- \ Copy current top number of P-stack to top of Forth's
- \ data stack. Note: P-stack is not changed.
- : P@ ( -- n D) ( n -- n P)
- P-INDEX @ P-STACK + @ ;
-
- \ Move number from top of P-stack to top of Forth's
- \ data stack. Note: Number is removed from P-stack.
- : P> ( -- n D) ( n -- P)
- P@ P-DEC ;
-
- \ Display all numbers on the P-stack.
- : .P ( -- )
- P-DEPTH ?DUP
- IF 1+ 1 ?DO I 2* P-STACK + @ 8 .R LOOP
- ELSE ." P-STACK EMPTY" THEN ;
-
-
- \ Problem 4.6 Personal User Stacks.
- \ Write Forth words for the following user stack operations. They should
- \ leave the data stack unchanged.
-
- \ PDUP PDROP PSWAP POVER PROT -PROT PTUCK PNIP 2PDUP 3PDUP 2PSWAP
- \ 2PDROP 2POVER
- \ Hint: : PSWAP ( n m -- m n P) P> P> SWAP >P >P ;
- \ Have we left out any important operators? Could you make
- \ P+ P- P* and P/ ????
-
-
- \ Solution to Problem 4.6
-
- : PDUP P@ >P ;
- : PDROP P> DROP ;
- : PSWAP P> P> SWAP >P >P ;
- : POVER P> P@ SWAP >P >P ;
- : PROT P> P> P> -ROT >P >P >P ;
- : -PROT PROT PROT ;
- : PTUCK PSWAP POVER ;
- : PNIP PSWAP PDROP ;
- : 2PDUP POVER POVER ;
- : 3PDUP P> 2PDUP DUP >P -PROT >P ;
- : 2PSWAP PROT P> PROT >P ;
- : 2PDROP PDROP PDROP ;
- : 2POVER 2PSWAP 2PDUP P> P> 2PSWAP >P >P ;
-
-