Coercion to a bignum

Coercion and opCall

At present, to get a new bignum we write something like:

auto a = new ZZ(12);

Notice that we can use auto instead of explicitly declaring the type. D has local type inference and infers the type from the expression itself. It can also infer return types of functions from the return statements. This makes life substantially easier.

What we would also like however, is the ability to turn an int into a ZZ, i.e. coerce the value. This is a concept which is germane to computer algebra. It comes about for example if I want to add two expression f = x^2 + 3 and g = (x^2 + 1)*y + (x^2 + 2). The first object lives in $\mathbb{Z}[x]$, whereas the second lives in $\mathbb{Z}[x][y]$. To add them together, f first needs to be coerced into $\mathbb{Z}[x][y]$ so that the two objects live in the same ring (have the same type).

Amazingly, D provides us with the ability to implement coercion. It allows us to overload the () operator, called the opCall operator. We’ll use it to allow us to write ZZ(1), for example, to coerce the int 1 into ZZ.

D allows us to overload the class’s opCall operator or to overload the opCall operator for object instances. The distinction between the two cases is that if you want to overload the class’s opCall you make the method static, otherwise you are overloading the opCall operator of objects of that given class. We will make use of the former in our code, since we want to write ZZ(1), not b(1) where b is a bignum.

In the case of coercing an int to a ZZ, all we need to do is create a new ZZ with the given int as value:

static ZZ opCall(int c) { return new ZZ(c); }

Now the following code works just fine:

auto a = ZZ(12);

We don’t need to use this functionality in the ZZ class itself. Ordinarily we might use it to coerce values into ZZ before adding them to other ZZ’s, etc. However, GMP has mpz_add_si, etc., and that will be much more efficient than coercing int’s to ZZ’s before adding them to other ZZ’s.

The opCall feature of D will prove extremely handy for implementing coercion between our rings of polynomials later on though!

‹‹‹ Previous Post Next Post ›››

Leave a Reply