A simple polynomial calculator in lisp

poly.cl 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. ;; Add two polynomials together
  2. (defun poly+ (poly1 poly2)
  3. (add-terms (append poly1 poly2) nil nil))
  4. ;; Subtract one polynomial from another
  5. (defun poly- (poly1 poly2)
  6. (add-terms (append poly1 (flip-multipliers poly2)) nil nil))
  7. ;; Returns the variable component of a singular polynomial
  8. (defun variable-symbol (single-poly)
  9. (car (car single-poly)))
  10. ;; Returns the exponent component of a singular polynomial
  11. (defun exponent (single-poly)
  12. (car (cdr (car single-poly))))
  13. ;; Returns the multiplier component of a singular polynomial
  14. (defun multiplier (single-poly)
  15. (car (cdr single-poly)))
  16. ;; Returns a polynomial with all the multipliers multiplied by -1
  17. (defun flip-multipliers (poly)
  18. (map 'list #'(lambda (x)
  19. (list (list (variable-symbol x) (exponent x))
  20. (* (multiplier x) -1))) poly))
  21. ;; Returns an added term if the addition is succesful, nil otherwise
  22. (defun term-addition (term1 term2)
  23. (if (and (equal (variable-symbol term1) (variable-symbol term2))
  24. (equal (exponent term1) (exponent term2)))
  25. (list (list (variable-symbol term1) (exponent term1))
  26. (+ (multiplier term1) (multiplier term2)))
  27. nil))
  28. ;; Returns the failed term if the addition fails, nil otherwise
  29. (defun term-failure (term1 term2)
  30. (if (and (equal (variable-symbol term1) (variable-symbol term2))
  31. (equal (exponent term1) (exponent term2)))
  32. nil
  33. term2))
  34. ;; This function replaces a full list of nils with the replace-term, otherwise
  35. ;; returns the list
  36. (defun useful-replace-nil (addition-seq replace-term)
  37. (if (equal (remove nil addition-seq) nil)
  38. (list replace-term)
  39. addition-seq))
  40. ;; Removes all zeroes from the polynomial
  41. (defun clear-zero (poly)
  42. (remove nil (map 'list #'(lambda (x)
  43. (if (equal (multiplier x) 0) nil x)) poly)))
  44. ;; Recursively adds all the terms in the list
  45. (defun add-terms (poly orig_var curr_var)
  46. (cond
  47. ((and (equal orig_var curr_var) (not (equal orig_var nil))) (clear-zero poly))
  48. (T (add-terms (remove nil (append (map 'list #'(lambda (x)
  49. (term-failure (car poly) x))
  50. (cdr poly))
  51. (useful-replace-nil (map 'list #'(lambda (y)
  52. (term-addition (car poly) y))
  53. (cdr poly)) (car poly))))
  54. (if (equal orig_var nil) (car (car poly)) orig_var)
  55. (car (car (cdr poly)))))))
  56. ; (poly+ '(((x 2) 3)) '(((y 2) 4)))
  57. ; (poly+ '(((x 2) 3) ((y 2) 3)) '(((y 2) 4)))