How to derive own distinguish type from Int?

Viewed 261

I would like to define two data types in Perl 6 deriving from Int but being incompatible with Int or each other at the same time.

For instance:

  • Distance derived from Int with a range 0 up to 32000, and
  • Offset derived from Int with a range from -32000 up to 32000

I would like the types Distance, Offset and Int being distinguishable and incompatible to each other on default.

So (pseudo Perl 6):

  my Distance $d = Distance(12);  // ok
  my Offset $o = Offset(-1);      // ok
  my Distance $d2 = $o;           // BUMMER!

  sub myprint(Int $i) { say $i }

  say $d + $o;                    // BUMMER!
  myprint $d;                     // BUMMER!
  myprint Int($d);                // ok

And so on! I want the Perl 6 compiler to complain if I ever try to mix Distances and Offsets implicitly.

In the books I've read so far there was no hint how to achieve this. Asking Google for some days also offer me no any answer whether this is possible, and if it is, how?

I found about subset but this only put some restriction on a type, but does not render it incompatible to the original type. Furthermore it is not distinguishable from the original type if its restrictions are met in both the original type and its subset.

So I would like to ask here if anybody know if this is possible in Perl 6? And if yes, how would I have to do it?

2 Answers
Related