6.001 FT04 - recitation 11 Tagged Data variable (define *variable-tag* 'variable) (define (make-variable vname) (list *variable-tag* vname)) (define (variable? x) (tagged-list? x *variable-tag*)) (define (varname var) (if (variable? var) (cadr var) (error "not a variable: " var))) (define (variable=? v1 v2) (eq? (varname v1) (varname v2))) constant-add (define (constant-add c1 c2) (make-constant (+ (constval c1) (constval v2)))) poly-add (define (poly-add p1 p2) (define (add-terms t1 t2) (cond ((null? t1) t2) ((null? t2) t1) (else (cons (add (car t1) (car t2)) (add-terms (cdr t1) (cdr t2)))))) (if (and (poly? p1) (poly? p2)) (if (variable=? (poly-get-var p1) (poly-get-var p2)) (make-poly (poly-get-var p1) (add-terms (poly-get-terms p1) (pol-get-terms p2))) (make-poly (poly-get-var p1) (cons (add (car (poly-get-terms p1)) p2) (cdr (poly-get-terms p1))))) (error "not given two polys"))) basic add procedure Hard to do without promotion, see below. promotion (define (var->poly var) (make-poly var (list 0 1))) (define (const->poly var const) (make-poly var (list const))) (define (->poly var exp) (cond ((constant? exp) (const->poly var exp)) ((variable? exp) (var->poly exp)) ((poly? exp) exp) (else (error "unknown exp" exp)))) (define (add e1 e2) (if (and (constant? e1) (constant? e2)) (constant-add e1 e2) (let ((var (find-var e1 e2))) (poly-add (->poly var e1) (->poly var e2))))