(* polynomials in ML *) datatype termType = pair of real * int; fun termAdd(pair(c1,e1), pair(c2,e2)) = if e1 = e2 then pair(c1+c2, e1) else (print "error, terms don't match"; pair(0.0, 0)); fun termPlusPoly(termIt:termType, []) = [termIt] | termPlusPoly((termIt as pair(tc, te)):termType, (x as pair(firstc, firste))::xs) = if te = firste then termAdd(termIt, x)::xs else x::termPlusPoly(termIt, xs); fun polyPlusPoly([], y) = y | polyPlusPoly(x, []) = x | polyPlusPoly((x as pair(xc,xe))::xs, (y as pair(yc,ye))::ys) = if xe > ye then x::polyPlusPoly(xs, y::ys) else if xe < ye then y::polyPlusPoly(x::xs, ys) else termAdd(x,y)::polyPlusPoly(xs,ys); fun isZero([]) = true | isZero((x as pair(xc, xe))::xs) = if (xc <= 0.0 andalso xc >= 0.0) andalso isZero(xs) then true else false; fun printTerm(pair(coeff,expo)) = if expo = 0 then print (Real.toString(coeff)) else if expo = 1 then print (Real.toString(coeff)^"X") else print (Real.toString(coeff)^"X^"^Int.toString(expo)); fun printPoly([]) = print "\n" | printPoly(x::[]) = (printTerm(x); print("\n")) | printPoly(x::(pair(tc, te)::xs)) = ( printTerm(x); if tc > 0.0 then print "+" (* print the connecting plus *) else print "" (* nothing *); printPoly((pair(tc, te)::xs))); (* p1 = ((3,4),(5,3),(1,2),(4,0)) which is 3x^4+5x^3+x^2+4 p2 = ((4,5),(2,1)) which is 4x^5+2x p3 = ((-2,2),(3,1),(6,0)) which is -2x^2+3x+6, and p4 = ((0,0)) i.e. the zero polynomial. *) val poly1 = [pair(3.0,4), pair(5.0,3), pair(1.0,2), pair(4.0,0)]; printPoly(poly1); val poly2 = [pair(4.0,5), pair(2.0,1)]; printPoly(poly2); val poly3 = [pair(~2.0,2), pair(3.0,1), pair(6.0, 0)]; printPoly(poly3); val poly4 = [pair(0.0,0)]; printPoly(poly4); print "p1+p2 is"; printPoly(polyPlusPoly(poly1, poly2)); print "p3+p4 is"; printPoly(polyPlusPoly(poly3, poly4)); print "p2+p3 is"; printPoly(polyPlusPoly(poly2, poly3)); print "is poly1 zero?"; isZero(poly1); print "is poly2 zero?"; isZero(poly2); print "is poly3 zero?"; isZero(poly3); print "is poly4 zero?"; isZero(poly4);