(defun coef (t) (car t) ) (defun var (t) (cadr t) ) (defun pow (t) (caddr t)) (defun collectaux (p q) ;collects first "collecting" term of q with p, returns either the sum of the collecting terms, or nil. (cond ((atom q) (progn (print q) ())) ;loop terminates here ((atom p) (progn (print p) ())) ;terminate here ((atom (car q)) ()) ((and (equal (var p) (var (car q))) (equal (pow p) (pow (car q)))) ;if so, we can add them together (progn (print "add") (setq nonadder (append nonadder (cdr q) ) ) (print nonadder) ;loop ends so we need to keep the terms we haven't added (cons (+ (coef p) (coef (car q))) ;add the coefficients (cons (var p) ;and append them with the var (cons (pow p) nil) ;and the pow ) ) ) ) (t (progn (setq nonadder (append nonadder (car q)));car q won't add to p, so put it here (print "won't add") (if (atom (cdr (car q))) () (progn (print "okay") (cons nil (collectaux p (cdr q))) ;check through the rest of q ) ) ) ) ) ) (defun collectauxplus (p) ;this auxilary function runs collaux on our list until all terms have been added (if (atom p) ;returns all of the "added together" terms together with the "haven't added" terms (cons p nonadder) (if (atom (car p)) (cons (car p) nonadder) (progn (setq nonadder ()) ;we keep the values that won't collect in here (progn (setq collaux (collectaux (car p) (cdr p))) ;we will use this value more than once, so store it (if (equal collaux '()) (cons (car p) (collectauxplus nonadder)) (cons collaux (collectauxplus nonadder)) ) ) ) ) ) ) (defun collect (p) ;this runs collectauxplus again and again until we see no changes- i.e. we have fully collected our terms. (progn (setq cap (collectauxplus p)) ;load this value once as we use it twice (if (equal () cap) p (if (equal p cap) p (collect cap) ) )) )