Posts Tagged ‘modulo’

div and mod

June 7, 2010

After consideration and looking at what Rakudo actually does, I decided the right solution to the div and mod issue was to change them in the Spec. In particular, I see them as having one interesting use: with integer types, they can always return the same integer type as their result, because either’s result will never have greater magnitude than its operands. I’ve rewritten their definitions to correspondingly tighten them as only working on integer types.

Real Operators

June 7, 2010

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.


Follow

Get every new post delivered to your Inbox.