Forth
1 Install
2 Usage
3 Commands
exit
help
+
drop
dup
over
swap
push
show
:
4 Example
7.1

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.

syntax

(exit)

End the program or REPL session immediately.

syntax

(help maybe-cmd)

If no arguments is given, print the current list of commands. Otherwise, print known information about the symbol maybe-cmd.

syntax

(+ - * /)

Pop the top two values from the stack, perform an arithmetic operation, push the result back on the stack.

syntax

(drop)

Delete the top item from the stack.

syntax

(dup)

Duplicate the top item of the stack.

syntax

(over)

Duplicate the top item of the stack, but save the result as the 3rd item on the stack.

syntax

(swap)

Switch the positions of the top two items on the stack.

syntax

(push N)

N
Put the number N on the stack.

syntax

(show)

Print the current stack.

syntax

(: id cmd* ...)

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
+