content="Data-structures and algorithms in Standard ML. Notes from a lecture course given by Michael Fourman at the University of West Australia, Spring 1994." /> rel="start" type="text/html" href="/mfourman/index.html" title="Michael Fourman" /> Solutions – Practical 3

Solutions – Practical 3

Michael P. Fourman

October 31, 2006

Poly.ML

Addition of polynomials is straightforward. This style of synchronised recursion, on two lists at once, is common.

Multiplication is more involved. The expression (map (times a) bb) multiplies each member of the list bb by a — the use of map hides an inner recursion. This inner recursion is analogous to one line of a long multiplication sum. In long multiplication, the remaining lines have to be shifted to multiply by 10; in polynomial multiplication, we shift (by consing 0.0) to give the effect of multiplication by x.

Evaluation directly implements Horner’s rule.

Differentiation and integration are handled by introducing auxiliary functions, with an additional parameter to keep track of the power of x. In each case, we have to treat the constant term specially.

SparsePoly.ML

We keep the lists of terms in order of increasing powers of x. Our implementation of addition relies on this, and this property is preserved by the other operations.

Note the use of layered patterns in the definition of polynomial addition. This reduces the syntactic overhead of the record syntax. This style of recursion, keeping two ordered lists in step, is also common.

Multiplication is just as before; but this time we introduce an auxiliary function to handle a single line of the sum, and since powers are carried in the terms, we don’t need an explicit shift.

Evaluation uses the explicit powers; Horner’s rule is only good for dense polynomials.

Differentiation and integration can be done term-by term; again there is a special case for differentiation of a constant.

©Michael Fourman 1994-2006