Forth (programming Language) - Programmer's Perspective

Programmer's Perspective

Further information: Reverse Polish notation

Forth 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:

25 10 * 50 + . 300 ok

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 DUPed 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:

int floor5(int v) { return (v < 6) ? 5 : (v - 1); }

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 ok

First 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:

    All things being equal, I would choose a woman over a man in order to even the balance of power, to insinuate a different perspective into the process, to give young women something to shoot for and someone to look up to. But all things are rarely equal.
    Anna Quindlen (b. 1952)