;; The first three lines of this file were inserted by DrScheme. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "reader.ss" "plai" "lang") ;; A simple interpreter for addition and subtraction. ;; ;; Morgan McGuire morgan@cs.williams.edu ; Grammar (define num? number?) (define (add? e) (and (list? e) (equal? (length e) 3) (eq? (first e) '+))) (define (sub? e) (and (list? e) (equal? (length e) 3) (eq? (first e) '-))) (define (expr? e) (or (num? e) (add? e) (sub? e))) ; The calc evaluator (interpreter) (define (calc e) (cond ; Value of a number is itself [(num? e) e] ; Value of a sum is the sum of the evaluation of its arguments [(add? e) (let ([lhs (second e)] [rhs (third e)]) (+ (calc lhs) (calc rhs)))] ; Value of a difference is the difference of the evaluation of its arguments [(sub? e) (let ([lhs (second e)] [rhs (third e)]) (- (calc lhs) (calc rhs)))])) (calc '(+ 1 2))