4 ms·
Haskell provides two functions for integer division, div and quot, and two functions for modulus, mod and rem. quot rounds towards 0, and div rounds towards neg
by lalaithion 5y ago
Haskell provides two functions for integer division, div and quot, and two functions for modulus, mod and rem. quot rounds towards 0, and div rounds towards negative infinity. rem is quot's modulus, and mod is div's modulus.
mod is Python's %, rem is C's %.
- tialaramex 5y agoIn Rust, the integer types [even the unsigned ones where it makes no difference] provide rem_euclid() that gives you a non-negative answer, whereas % is defined to have the same sign as your dividend if it isn't zero. Having this for unsigned types allows you to write rem_euclid() if that's definitely what you meant even when you aren't sure if the type you'll be using here will be signed (and thus it matters) or not. Unfortunately Rust's std::ops::Rem trait (the trait which provides the overloadable % operator) does not offer this alternative, so if all you know about a type is that you can apply the modulus operator to it, you only get that operator and there's no uniform way to get a Euclidean remainder instead.
- bjoli 5y agoScheme is the same, since at least r4rs, which came out in 1991. Not having it is, I would argue, bad taste.
- yakubin 5y agoIt's a bit different: Scheme: > (mod 5 2) 1 > (mod 5 -2) 1 > (mod -5 2) 1 > (mod -5 -2) 1 > (remainder 5 2) 1 > (remainder 5 -2) 1 > (remainder -5 2) -1 > (remainder -5 -2) -1 Haskell: Prelude> a = 5 :: Integer Prelude> b = 2 :: Integer Prelude> mod a b 1 Prelude> mod a (-b) -1 Prelude> mod (-a) b 1 Prelude> mod (-a) (-b) -1 Prelude> rem a b 1 Prelude> rem a (-b) 1 Prelude> rem (-a) b -1 Prelude> rem (-a) (-b) -1 So in Scheme mod is the Euclidean modulus (always >= 0) and remainder takes the sign of the dividend (comes from truncated division, same as C's %). In Haskell mod takes the sign of the divisor (floored division, same as Python), while rem behaves the same way as Scheme's remainder or C's %. I prefer Scheme's way, because it was what we always used in classes when I studied maths. mod returning a negative number is just too weird. EDIT: It appears that Scheme also has modulo, which comes from floored division: > (modulo 5 2) 1 > (modulo 5 -2) -1 > (modulo -5 2) 1 > (modulo -5 -2) -1
- bjoli 5y agoR6RS specifies div, mod, div0 and mod0 and specifies their semantics.