A simple polynomial calculator in lisp

poly.cl 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. ;; Add two polynomials together
  2. (defun poly+ (poly1 poly2)
  3. (add-terms (append poly1 poly2)))
  4. ;; Subtract one polynomial from another
  5. (defun poly- (poly1 poly2)
  6. (add-terms (append poly1 (flip-multipliers poly2))))
  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. ;; Returns true if a polynomial contains only unique terms
  35. (defun poly-unique-terms? (poly)
  36. (cond ((equal poly nil) T)
  37. (T (if (some #'(lambda (x) (equal (car x) (car (car poly)))) (cdr poly))
  38. nil
  39. (poly-unique-terms? (cdr poly))))))
  40. ;; This function replaces a full list of nils with the replace-term, otherwise
  41. ;; returns the list
  42. (defun useful-replace-nil (addition-seq replace-term)
  43. (if (equal (remove nil addition-seq) nil)
  44. (list replace-term)
  45. addition-seq))
  46. ;; Removes all zeroes from the polynomial
  47. (defun clear-zero (poly)
  48. (remove nil (map 'list #'(lambda (x)
  49. (if (equal (multiplier x) 0) nil x)) poly)))
  50. ;; Recursively adds all the terms in the list
  51. (defun add-terms (poly)
  52. (cond
  53. ((poly-unique-terms? poly) (clear-zero poly))
  54. (T (add-terms (remove nil (append (map 'list #'(lambda (x)
  55. (term-failure (car poly) x))
  56. (cdr poly))
  57. (useful-replace-nil (map 'list #'(lambda (y)
  58. (term-addition (car poly) y))
  59. (cdr poly)) (car poly))))))))
  60. ; (poly+ '(((x 2) 3)) '(((y 2) 4)))
  61. ; (poly+ '(((x 2) 3) ((y 2) 3)) '(((y 2) 4)))