'What's the point of Raku's 'mod' operator?
I previously incorrectly thought that the % operator returned the remainder and the mod operator returned the modulus (the remainder and modulus are the same when the operands are both positive or both negative but differ when one operand is positive and the other is negative. Compare Raket's remainder and modulo functions).
However, that's not correct at all – both % and mod return the modulus; neither return the remainder. In fact, it looks like mod will always return exactly the same value as % would have, if called with the same arguments. As far as I can tell, the only difference is that % can be called with non-integer arguments, whereas mod throws an exception if called with anything other than Int:D or int.
So, what's the point of mod? Is there some performance gain from using it (maybe by saving the optimizer some specialization work?) or is there some other difference I'm missing?
Solution 1:[1]
TL;DR My takeaway from a quick skim of sources is that % is (supposed to be) the rational or generic modulus op, whereas mod is a dedicated integer modulus op. For some inputs they yield the same result.
The rest of this answer just references the sources I looked at.
Doc
mod:
Integer modulo operator. Returns the remainder of an integer modulo operation.
%:
Modulo operator. Coerces to
Numericfirst.Generally the following identity holds:
my ($x, $y) = 1,2; $x % $y == $x - floor($x / $y) * $y
roast
Search of roast for modulus lists just S03-operators/arith.t. Leads to:
"TimToady thinks
modmap(or whatever we decide to call it) would be a useful addition to the language". (Off topic but interesting.)
S03
infix:<%>, modulocoerces ... then calculates the remainder ... defined as:
$x % $y == $x - floor($x / $y) * $yIf both operands are of integer or rational type, the operator returns the corresponding
Ratvalue (except when the result does not fit into aRat, as detailed in S02).
infix:<mod>, integer moduloDispatches to the
infix:<mod>multi most appropriate to the operand types, returning a value of the same type. Not coercive, so fails on differing types.This should preserve the identity:
$x mod $y == $x - ($x div $y) * $y
IRC
Search of #perl6 for mod integer.
Rakudo source code
Solution 2:[2]
The 'bible' of IEEE P754 says this...
Floating point remainder. This is not like a normal modulo operation, it can be negative for two positive numbers. It returns the exact value of x–(round(x/y)·y).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
