Thoughts on Real

I’ve been musing on this for about a month now, meaning to write it up. Since I discussed the basic idea last night on #perl6 with Larry, I guess now is as good a time as any. (Note that Larry did not endorse the idea at the time, but he didn’t shoot it down, either.)

My notion is that the Real role needs to have a lingua franca type, which I’ll call RealX for the moment. If every type that does Real defines a RealX conversion function, then Real can provide sensible default versions of most of the things the Real role needs to do.

For example, last night the issue was comparing an Int and a Rat using cmp. It turns out that in Rakudo, cmp has a case for comparing two Nums (and Int is a type of Num), but Rat was not included. This means it fell back to its default string comparison when passed an Int and a Rat, which is a Bad Thing. For the moment, I solved the issue in the series branch by adding versions of cmp which were Rat-aware.

But ideally, we’d like to be able to compare any two classes which do the Real role, even if those two classes know nothing about each other. Without some notion of a lingua franca for Real, this is a huge headache. With a lingua franca RealX, though, the implementation is trivial:

multi sub infix:<cmp>(Real $a, Real $b) {
$a.RealX <=> $b.RealX;
}

That’s all that’s need to make cmp work correctly for any pair of future Real classes that might be written (assuming they both implement the .RealX conversion).

But the notion doesn’t stop there. It would allow us to provide sensible default versions of most of the methods and subs on Real:

The effect would be twofold. It would allow otherwise unrelated Real types to work together pretty seamlessly. But it would also greatly simplify fully implementing new Real types, as the default versions of many of the Real methods would be all most types would ever need.

That’s about all that would be needed to create a fully functional Real type. In practice, of course, you’d probably want to provide a custom .Str method and operators for addition, subtraction, multiplication, and comparison between two Dollars or a Dollar and and an Int.

I’ve purposely left the question of what type RealX should be for a later post, not least because I have no clear winner yet for what the best type would be.