February 19, 2009
The only difficulty is handling the newline, which the Scheme reader treats as whitespace. The
(op token) function converts
token from a symbol returned by the reader to an operator that can be used to perform arithmetic. The format of the first line of the program is specific to Chez Scheme, but most Scheme systems provide something similar.
#! /usr/bin/scheme –script
(cond ((eof-object? (peek-char)) (exit))
((char=? (peek-char) #\space) (read-char) (next))
((char=? (peek-char) #\newline) (read-char) ‘nl)
(define (op token) (case token ((+) +) ((-) -) ((*) *) ((/) /)))
(let rpn ((token (next)) (stack ‘()))
(cond ((eq? ‘nl token) (display (car stack)) (newline) (rpn (next) (cdr stack)))
((number? token) (rpn (next) (cons token stack)))
(else (rpn (next) (cons ((op token) (cadr stack) (car stack)) (cddr stack))))))
Although it can’t be run, this program is available as a paste at http://programmingpraxis.codepad.org/fjzlC50x. This exercise was inspired by a web page of Fredrik Arnerup at http://www.stacken.kth.se/~foo/rpn.
Pages: 1 2