I decided to work on the operators for Real tonight. First up was adding tests I skipped writing before, for the Real / Bridge versions of infix `+, *, and /`

. Then I implemented a completely generic version of infix `%`

for Real, and added tests for it.

And then I ran into the tricky bit: `div`

and `mod`

. `div`

is division which generates a result of the same type as the two operands. So for instance, `5 / 4 == 1.25`

— two Ints divided to get a Rat. But `5 div 4 == 1`

. This is perfectly straightforward and sensible, but how do you implement a generic version that does this? It seems like each type descended from Real will have to define its own `div`

. And it won’t necessarily be easy, either — I’m not sure how to sensibly do it for Rat, for instance. You can’t fall back to outputting a Num if things get out of hand.

It gets even worse with `mod`

. The spec says that for built-in types, `$x mod $y == $x - ($x div $y) * $y`

. That makes `mod`

the equivalent of `%`

for integer types. But for non-integer types, `div`

should be closer to normal division, in which case `mod`

will always return zero or possibly a small error value. IMO the spec is poorly defined here, but I’m not yet seeing how to improve it.

Thanks to the Perl Foundation and Ian Hague for supporting this work.

### Like this:

Like Loading...

*Related*

Tags: modulo, Numeric

This entry was posted on June 7, 2010 at 2:19 am and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

## Leave a Reply