[ ^ CSE 341 | section index | <-- previous ]

Homework overview

Write and test a set of Scheme functions to do algebraic simplification of arithmetic expressions . . .

;; top-level function -- simplify an expression (define (simplify expr) (cond ((number? expr) expr) ; number simplifies to itself ((symbol? expr) expr) ; can't further simplify a symbol either ;; if the expression is an addition or a multiplication, first ;; simplify each argument, using a recursive call, then simplify ;; the sum or product ((plus-expr? expr) (plus-simplify (simplify (second expr)) (simplify (third expr)))) ((times-expr? expr) (times-simplify (simplify (second expr)) (simplify (third expr)))) (else (error "unknown type of expression")))) ;; test whether an expression is an addition (define (plus-expr? expr) (and (list? expr) (eq? (car expr) '+))) ;; test whether an expression is a multiplication (define (times-expr? expr) (and (list? expr) (eq? (car expr) '*))) (define (plus-simplify e1 e2) (cond ((and (number? e1) (number? e2)) (+ e1 e2)) ((and (number? e1) (zero? e1)) e2) ; 0 plus x is x ((and (number? e2) (zero? e2)) e1) (else (list '+ e1 e2)))) ; couldn't simplify (define (times-simplify e1 e2) (cond ((and (number? e1) (number? e2)) (* e1 e2)) ((and (number? e1) (zero? e1)) 0) ; 0 times anything is 0 ((and (number? e2) (zero? e2)) 0) ((and (number? e1) (= e1 1)) e2) ; 1 times x is x ((and (number? e2) (= e2 1)) e1) (else (list '* e1 e2)))) ; couldn't simplify

Last modified: Wed Mar 29 19:55:38 PST 2000