Sunday, September 27, 2009

Polynomial and <<+>>

Defining a one-variable polynomial class is actually a pretty straightforward thing. We use a standard Perl 6 array to hold the polynomial's coefficients, with the Nth element of the array representing the coefficient of x^N. You can check out the complete source if you'd like; for the most part, Perl 6's nifty hyperoperators and list operations make the implementation simple.

One example where that isn't true is simple polynomial addition. In principle, this is the simplest thing possible; you just do a pairwise add on all the coefficients of the two polynomials. The only catch is when the polynomials have different degrees, so the arrays have different sizes. In that case we'd like to pad the array with zeros. Unfortunately, <<+>> pads with the last element of the shorter array, with is completely mathematically unsuitable in this case. So here was my first stab at implementing Polynomial addition:


That sort of thing works, but seems more like it belongs in the ugly world of C++ than the elegant world of Perl 6. The subject came up on the #perl6 channel yesterday, and pmichaud++ came up with a nice workaround: $a.coefficients, 0 <<+>> $b.coefficients, 0. As it is, this adds an additional zero coefficient each time it is called, which in the long run will be trouble. But it can be counteracted by adjusting the Polynomial constructor to remove "trailing" zero coefficients. (This is how Polynomial.pm is currently implemented.) (Errr... perhaps I spoke too soon; I'm having difficulty successfully deleting the trailing zeros. Sigh.)

On the IRC chat, colomon suggested using an adverb to tell <<+>> how to extend. His suggestion of :extend-with seems like a weak name to me, but I do think it seems like the proper Perl 6ish way to handle this issue.

No comments:

Post a Comment