Programmer's Perspective
Further information: Reverse Polish notationForth relies heavily on explicit use of a data stack and reverse Polish notation (RPN or postfix notation), commonly used in calculators from Hewlett-Packard. In RPN, the operator is placed after its operands, as opposed to the more common infix notation where the operator is placed between its operands. Postfix notation makes the language easier to parse and extend; Forth's flexibility makes a static BNF grammar inappropriate, and it does not have a monolithic compiler. Extending the compiler only requires writing a new word, instead of modifying a grammar and changing the underlying implementation.
Using RPN, one could get the result of the mathematical expression (25 * 10 + 50)
this way:
This command line first puts the numbers 25 and 10 on the implied stack.
The word *
multiplies the two numbers on the top of the stack and replaces them with their product.
Then the number 50 is placed on the stack.
The word +
adds it to the previous product. Finally, the .
command prints the result to the user's terminal.
Even Forth's structural features are stack-based. For example:
: FLOOR5 ( n -- n' ) DUP 6 < IF DROP 5 ELSE 1 - THEN ;This code defines a new word (again, word is the term used for a subroutine) called FLOOR5
using the following commands: DUP
duplicates the number on the stack; 6
places a 6 on top of the stack; <
compares the top two numbers on the stack (6 and the DUP
ed input), and replaces them with a true-or-false value; IF
takes a true-or-false value and chooses to execute commands immediately after it or to skip to the ELSE
; DROP
discards the value on the stack; and THEN
ends the conditional. The text in parentheses is a comment, advising that this word expects a number on the stack and will return a possibly changed number. The FLOOR5
word is equivalent to this function written in the C programming language using the ternary operator:
This function is written more succinctly as:
: FLOOR5 ( n -- n' ) 1- 5 MAX ;You would run this word as follows:
1 FLOOR5 . 5 ok 8 FLOOR5 . 7 okFirst the interpreter pushes a number (1 or 8) onto the stack, then it calls FLOOR5, which pops off this number again and pushes the result. Finally, a call to "." pops the result and prints it to the user's terminal.
Read more about this topic: Forth (programming Language)
Famous quotes containing the word perspective:
“No one thinks anything silly is suitable when they are an adolescent. Such an enormous share of their own behavior is silly that they lose all proper perspective on silliness, like a baker who is nauseated by the sight of his own eclairs. This provides another good argument for the emerging theory that the best use of cryogenics is to freeze all human beings when they are between the ages of twelve and nineteen.”
—Anna Quindlen (20th century)