recip for Ratio

Simon Peyton-Jones simonpj@microsoft.com
Tue, 3 Apr 2001 03:45:32 -0700


Folks,

I'm finally getting back to revising the Haskell 98 report, you'll
be glad to hear.  So I'll be emitting a few consultative messages.
This is the first.

Scott Turner points out:

| In the Haskell 98 Library Report, recip is defined for the=20
| Ratio type as:
|     recip (x:%y)  =3D  if x < 0 then (-y) :% (-x) else y :% x
|=20
| Is it intentional that=20
|     recip (0 % 1)
| is not an error?  Everywhere else the denominator is forced=20
| to be positive.  Infinity can be a useful number, if the type=20
| is consistent about it.

He's right.  Everywhere else in the Ratio library we use '%'
to construct rationals, a smart constructor that enforces the
invariant that the denominator is positive and nonzero, and
the numerator and denominator have no common divisor.

It seems that the above specification for recip is guilty of
premature optimisation.  We should instead define it as

	recip (x :% y) =3D y % x

leaving the smart constructor to enforce the invariant.  An
implementation might optimise this, knowing that x and y have
no common divisor, but that is not the role of a specification.

Any objections to this change?=20

Simon