help with multiplying polynomials in lisp
for example: (3x2 - 5x + 2)(7x + 1) 开发者_如何学JAVAand you simplify it like this:
((3 2)(-5 1)(2 0))((7 1)(1 0))
((21 3)(3 2)(-35 2)(-5 1)(14 1)(2 0))
(21 3)(32 2)(9 1)(2 0)
and you get this answer: 21x3 + 32x2 + 9x + 2
i need this solution in lisp please help
For the first stage, you need to pair up every LHS component with every RHS component; a cartesian product of the two sets. This requires a two-level map followed by a concatenation of the second-level lists of pairs into a single top level list (think (apply #'append ...
).
The second stage can be done with a reduce that builds up an association list, keyed on the exponent.
EDIT: Let me solve a different problem for you, and let you figure out how to translate it into the solution for your problem:
Compute (a + b + ... + k) * (l + m + ... + z)
by first expanding into pairs and then summing the products:
(defun mul-sums (aa bb)
(reduce #'+
(apply #'append
(map 'list
#'(lambda (a)
(map 'list
#'(lambda (b)
(* a b))
bb))
aa))))
; Compute (1 + 2 + 3) * (3 + 4).
> (mul-sums '(1 2 3) '(3 4))
42
精彩评论