Version 1 of Minimal RPN

Updated 2004-01-13 17:53:21

if 0 {Richard Suchenwirth 2004-01-13 - In RPN in Tcl I've played a bit with emulating Forth in Tcl. Here is a much shorter take that defines a single rpn proc, which takes a body in Reverse Polish Notation, and the rest of the arguments as the initial stack. The words in the body are executed from left to right, either as Forth-like stack operations, or as a Tcl command which has to have one argument (popped from stack) and whose result is pushed on the stack.}

 proc rpn {body args} {
    foreach word $body {
        switch -- $word {
            drop {pop args}
            dup  {push args [lindex $args end]}
            swap {set 1 [pop args]
                set 2 [pop args]
                push args $1 $2
            }
            default {push args [$word [pop args]]}
        }
    }
    set args
 }

# Simple stack routines:

 interp alias {} push {} lappend
 proc pop stackName {
    upvar 1 $stackName stack
    K [lindex $stack end] [set stack [lrange $stack 0 end-1]]
 }

# ..and the indispensable K combinator:

 proc K {a b} {set a}

# This test will display the source file on stdout:

 puts [rpn {open dup read swap close drop} rpn.tcl]

Arts and crafts of Tcl-Tk programming