I need to store polynomials in my lisp program for adding, subtracting and multiplying. But cannot find an easy way of storing one.
I've considered the following way
(2x^3 + 2x + 4y^3 - 2z) in a list of lists where each list is a list of the amount of each power
= ( (0 2 0 2) (0 0 0 4) (0 2) )
But the uncertain lengths of each list and potential length could become a problem.
Is there a generally accepted way to store them in lisp which could make it as easy as possible to add, subtract and multiply them together?
Assuming you know the number of possible variables beforehand, you could express each term like this:
(constant x-exponent y-exponent z-exponent ...)
. Then5xy^2
would be(5 1 2 0)
, and a full expression would just be a list of those terms.If you want to be able to handle any number of arbitrary variables, you would need to do an associative list along the lines of
((constant 5) (a 0) (b 3) (z 23) (apple 13))
.Either way, if you start with individual terms, it's easy to build more complex expressions and this way you don't need to mess with multiple dimensions.