Guest User

Untitled

a guest
May 15th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 1.96 KB | None | 0 0
  1. (defun p* (p1 p2)
  2.   "Multiplies the two given polynomials together."
  3.     (mapcan #'(lambda (x)
  4.       (mapcan #'(lambda (y)
  5.         (list (cons (* (car x) (car y)) (concatenate 'list (cdr x) (cdr y))))
  6.         ) p1)
  7.     ) p2)
  8.   )
  9.  
  10. (defun merge-variables (input &optional output)
  11.   "Recursively collects terms given the original input"
  12.   ;(print input)
  13.   ;(print output)
  14.   (if (null input)
  15.     (return-from merge-variables output)) ; input is exhausted, so return output
  16.   (merge-variables
  17.         (mapcan #'(lambda (x)
  18.           (if (not (equal (caar input) (car x)))
  19.               (list x) )          
  20.         ) input) ; new input list will contain all variables not equal to the current variable.
  21.        
  22.         (check-for-zero-exponential (list (caar input)
  23.           (apply #'+ (mapcan #'(lambda (x)                                            
  24.             (if (equal (caar input) (car x))
  25.              (cdr x))                                    
  26.         ) input))) output) ; current variable (with accumulated exponents) will
  27.                        ; be appended to the output list (providing its exponent is non-zero).
  28.    )  
  29. )
  30.  
  31. (defun check-for-zero-exponential (variable-with-expo output)
  32.   "If exponent is non-zero, append to output. Otherwise, returns the output"
  33.   (if (eq 0 (cadr variable-with-expo))
  34.     (return-from check-for-zero-exponential output)
  35.     (return-from check-for-zero-exponential (concatenate 'list output (list variable-with-expo))))
  36.   )
  37.  
  38. (defun evaluate-polynomial (p)
  39.   (mapcar #'(lambda (x)
  40.        ;(print x)
  41.        (cons (car x) (merge-variables (cdr x))) ; cons original coefficient onto simplified list of variables for that term
  42.     ) p)
  43.   )
  44.  
  45. (equal '((4 (X 5) (X 2)) (4 (X 5) (Y 1))) (p* '((2 (X 2)) (2 (Y 1))) '((2 (X 5))))) ; evaluates to true
  46. (evaluate-polynomial (p* '((2 (X 2)) (2 (Y 1))) '((2 (X 5))))) ; evalutes to ((4 (X 7)) (4 (X 7) (Y 1))) (incorrect)
  47. (evaluate-polynomial '((4 (X 5) (X 2)) (4 (X 5) (Y 1)))) ; evaluates to ((4 (X 7)) (4 (X 5) (Y 1))) (correct)
Add Comment
Please, Sign In to add comment