Reputation: 2262
The rem
in Haskell behaves just like the %
in JavaScript. When using the clock analogy rem
always goes clock-wise regardless if the value is positive or negative. rem
takes the sign of the divident
divident / divisor = quotient
Prelude> 10 `rem` 3
1
Prelude> -10 `rem` 3
-1
%
in JavaScript works the same way
$ node
> 10 % 3
1
> -10 % 3
-1
mod
behaves like rem
when both values are positive. The only difference is that when one of the numbers is negative mod
goes backwards on the clock, not clock-wise and takes the sign of the divisor.
Knowing that mod
and rem
give the same result when both numbers are positive which one is recommended to be used in Haskell?
Upvotes: 3
Views: 828
Reputation: 152837
div
and mod
are more semantically sensible, while quot
and rem
are marginally faster. So my advice is to use div
and mod
as a reflex, and only ever change to using quot
and rem
after doing a lot of work to make sure their performance is actually relevant to some slowdown you absolutely must fix and doing a lot of work to prove that it's safe. In the long run, subtle sign bugs are almost certainly going to cost you much more debugging time than subtle performance bugs will cost you computation time.
Upvotes: 6