8.12
Forth
(require forth) | package: forth |
Forth is a stack-based calculator language. This package implements a subset of Forth as a Racket #lang.
1 Install
To install from the package server, run:
raco pkg install forth
To install from source, run:
git clone https://github.com/bennn/forth raco pkg install ./forth
2 Usage
Files starting with #lang forth are interpreted as a newline-separated sequence of commands. Alternatively, run raco forth to start an interactive session.
3 Commands
These commands are the base environment, but the list of commands can grow as a program runs. Type help at any time to see the currently available commands.
End the program or REPL session immediately.
If no arguments is given, print the current list of commands.
Otherwise, print known information about the symbol maybe-cmd.
Pop the top two values from the stack, perform an arithmetic operation, push the result back on the stack.
Delete the top item from the stack.
Duplicate the top item of the stack.
Duplicate the top item of the stack, but save the result as the 3rd item on the stack.
Switch the positions of the top two items on the stack.
Put the number N on the stack.
Print the current stack.
Define a new command with name id as the composition of existing commands cmd* ....
Later calls to id will execute the commands cmd* ... in sequence, and later calls to help will display information about id.
4 Example
Running this program should produce the list (4 2). Forth programs always return their final stack. Note that "push 2" and "2" have the same effect.
#lang forth push 2 push 2 + dup 2 swap - swap : incr 1 + incr incr +