cs375 p. 269

Contents Page-10 Prev Next Page+10 Index

Interpreter

This program is an interpreter for arithmetic expressions using a simulated stack machine.

(defun topinterp (exp) ; interpret, pop result
 (progn (interp exp)
 (pop *stack*)))
(defun interp (exp)
 (if (consp exp) ; if op
 (if (eq (car exp) '+)
 (progn (interp (cadr exp)) ; lhs
 (interp (caddr exp)) ; rhs
 (plus)) ; add
 (if ...)) ; other ops
 (pushopnd exp))) ; operand
(defun pushopnd (arg) (push arg *stack*))
(defun plus ()
 (let ((rhs (pop *stack*)))
 (pushopnd (+ (pop *stack*) rhs))))
>(topinterp '(+ (* 3 4) 5))
17

AltStyle によって変換されたページ (->オリジナル) /