View
218
Download
1
Tags:
Embed Size (px)
Citation preview
Forth
Lecture L7.1
A Brief History of Programming Languages
http://www.byte.com/art/9509/sec7/art19.htm
http://merd.net/pixel/language-study/diagram.html
How would you have a computer evaluate this expression?
X = A*B + (C – D)/(E + F)
Reverse Polish Notation (RPN)Postfix
AB*CD-EF+/+
WHYP
• Pronounced “whip”
• “Words to Help You Program”
• Subroutine-threaded Forth for Embedded Systems– 68HC11 (16-bit)– 68332 (32-bit)– 68HC12 (16-bit)
WHYP is developed from scratch in the book:
Design of Embedded Systems Using 68HC12/11 Microcontrollers
byRichard E. HaskellPrentice Hall, 2000
FORTH is a programming language that ---
• was invented by Charles Moore in the early 70’s
• is extensible
• keeps all definitions in a dictionary
• is extremely compact
• is recursive
• can be programmed in RAM, PROM, or ROM
• is structured
• uses a stack and postfix notation
Chuck Moorereading Haskell’sWHYP book
WHYP Colon Definitions
: squared ( n -- n**2)DUP * ;
: cubed ( n -- n**3)DUP \ n n squared \ n n**2* ; \ n**3
Branching and Looping in WHYP
• IF…ELSE…THEN
• FOR…NEXT
• BEGIN…AGAIN
• BEGIN…UNTIL
• BEGIN…WHILE…REPEAT
IF…ELSE…THEN
<cond> IF <true statements>
ELSE<false statements>
THEN
<cond> is either TRUE (-1) or FALSE (0)
WHYP Conditional Words
< ( n1 n2 -- f ) (“less-than”)> ( n1 n2 -- f ) (“greater-than”)= ( n1 n2 -- f ) (“equals”)<> ( n1 n2 -- f ) (“not-equals”)<= ( n1 n2 -- f ) (“less-than or equal”)>= ( n1 n2 -- f ) (“greater-than or equal”)0< ( n -- f) (“zero-less”)0> ( n -- f) (“zero-greater”)0= ( n -- f) (“zero-equal”)U< ( u1 u2 -- f ) (“U-less-than”)U> ( u1 u2 -- f ) (“U-greater-than”)U<= ( u1 u2 -- f ) (“U-less-than or equal”)U>= ( u1 u2 -- f ) (“U-greater-than or equal”)
\ Convert hex to ASCIIHEX
: hex2asc ( n -- asc ) 0F AND \ mask upper nibble DUP 9 > \ if n > 9 IF 37 + \ add $37 ELSE 30 + \ else add $30 THEN ;
Do different things depending what is in T
: checkT ( n -- )DUP 1 = \ n fIF \ n DO1 \ELSE \ n DUP 2 = \ n f IF \ n DO2 ELSE \ n DUP 3 = \ n f IF \ n
DO3 ELSE \ n
DO4 THEN \ THENTHEN ;
>R
Decrement top of return stack and branch back to <WHYP statements> if not equal to zero.Therefore, <WHYP statements> are executedn times.
FOR…NEXT Loop
n FOR <WHYP statements> NEXT
drjne <WHYP statements>
BEGIN…AGAIN
BEGIN <WHYP statements> AGAIN
BEGIN…UNTIL
BEGIN <WHYP statements> <flag> UNTIL
<flag> is either TRUE or FALSEusually from some WHYP conditional word
: GET.BTN ( -- n ) BEGIN
BEGIN BTN@ 0=UNTILBEGIN BTN@
UNTILBTN@CHECKT
AGAIN ;
BEGIN…WHILE…REPEAT
BEGIN <words> <flag>
WHILE <words>
REPEAT
x = 1 i = 2 DO WHILE i <= n x = x * i i = i + 1 ENDDO factorial = x
: factorial ( n -- n! ) 1 2 ROT \ x i n BEGIN \ x i n 2DUP <= \ x i n f WHILE \ x i n -ROT TUCK \ n i x i * SWAP \ n x i 1+ ROT \ x i n REPEAT \ x i n 2DROP ; \ x
Factorial