This is another stab at multivariate polynomials. It does about what this does but better structured, I think. It forms a list of tools for polynomials with n variables, from the corresponding list for polynomials of n−1 variables. A polynomial of n variables is represented as a list of coefficients with the constant term first. Each coefficient is a polynomial in n−1 variables. Polynomials in 0 variables are numbers. The tool list is (addition, multiplication, negation, scalar multiply (number by polynomial), test for zero, (e p x) evaluates polynomial p at (car x) using e to evaluate each of the coefficients with (cdr x)).
(define (polpak tl)(apply (lambda (p+ p* neg sm zer? e vars) (let ((n+ (lambda (a b) (let add ((a a)(b b)) ; new + (if (null? a) b (if (null? b) a (let ((s (p+ (car a) (car b))) (t (add (cdr a) (cdr b)))) (if (and (zer? s) (null? t)) '() (cons s t))))))))) (list n+ ; new addition (lambda (a b) ; new product (let ((ms (lambda (a b) ; a is of degree n-1, b of degree n. (let ma ((b b)) (if (null? b) '() (cons (p* (car b) a) (ma (cdr b)))))))) (if (null? b) '() (let mb ((a a)) (if (null? a) '() (let ((fv (ms (car a) b))) (cons (car fv) (n+ (cdr fv) (mb (cdr a)))))))))) (lambda (a) ; new negation (let n ((a a)) (if (null? a) '() (cons (neg (car a))(n (cdr a)))))) (lambda (s a) ; new scalar multiply (let m ((a a)) (if (null? a) '() (cons (sm s (car a))(m (cdr a)))))) (lambda (a) ; new zero test (let z? ((a a))(or (null? a) (and (zer? (car a)) (z? (cdr a)))))) (lambda (m x) (let ep ((m m)) (if (null? m) 0 (+ (e (car m) (cdr x)) (* (car x) (ep (cdr m))))))) (list (list'() 1) (map list vars)) ; list of variables ))) tl)); tests
(define (X l v)(write (list l v)) (newline) v) (define reals (list + * - * zero? (lambda (x y) x) '())) (define w (polpak reals)) (define p+ (car w)) (define p* (cadr w)) (p* '(3) '(4)) (define q (cadr (cddddr w))) (q '(3 5) '(4)) (define w (polpak w)) (define p+ (car w)) (define p* (cadr w)) (define q (cadr (cddddr w))) (p* '((3 4) (3 4 5)) '((3 1 2) (6 4))) (q '((1 2) (2 3)) '(2 3))Tentative evaluator: (closest thing yet to semantics and syntax)
(define (ep x v)(if (null? x) 0 (if (number? x) x (+ (ep (car x) (cdr v)) (* (car v) (ep (cdr x) v))))))An improvement?