- #36
JamesBwoii
- 74
- 0
When you say sort by the variable and exponent you mean sort alphabetically for the variable and say sort from low to high for the exponent?Bacterius said:Looks fine to me, if a bit messy (I would personally first find the first two elements using "let", and then inside that let use these elements to access the variable and exponents for both of them, instead of starting from scratch from p1 every time).
So what's next now, say to get addition done? You need exactly one thing: a function to sort the list based on the variable + exponent, this will require you to read up on Lisp's sorting function. Call this function "sortpoly". Then, addition can be implemented as:
Here collect-terms is the function you call "poly", which we have been working on so far. Do you understand why addition can be implemented in this way? If so, implement sortpoly and addpoly.Code:(defun addpoly (p1 p2) (collect-terms(sortpoly(append p1 p2))) )
As a bonus, you might notice that if you use your "addpoly" function on, say, ((1(2 x)) and ((-1(2 x)) you will get ((0(2 x)). This is not technically wrong, but zero times anything is still zero, so see if you can implement a function to remove terms with a zero coefficient from a polynomial. You can use a recursive function in the same spirit as "poly"/"collect-terms" (by taking a look at the first element of the polynomial, checking if its constant is zero or not, discarding it if appropriate, and recursing on the rest of the polynomial).
I assume sorting by the variable is the priority so the whole list would be ordered alphabetically by variable then each group of the same variables would be ordered by exponent.
Then if two polynomials were being added together and had the same variable and exponent they could be added.