;; 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 add-lhs second)
(define add-rhs third)
(define (sub? e) (and (list? e) (equal? (length e) 3) (eq? (first e) '-)))
(define sub-lhs second)
(define sub-rhs third)
(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 (add-lhs e)]
[rhs (add-rhs e)])
(+ (calc lhs) (calc rhs)))]
; Value of a difference is the difference of the evaluation of its arguments
[(sub? e)
(let ([lhs (sub-lhs e)]
[rhs (sub-rhs e)])
(- (calc lhs) (calc rhs)))]))
;; Example
(calc '(+ 1 2))