4 ms·
It'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 >
by yakubin 5y ago
It'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.