开发者

'mod' and -1 in haskell [duplicate]

开发者 https://www.devze.com 2023-01-09 04:44 出处:网络
This question already has answers here: Integral operators quot vs. div (2 answers) Closed 8 years ago. how come that following piece gives 4?
This question already has answers here: Integral operators quot vs. div (2 answers) Closed 8 years ago.

how come that following piece gives 4?

(\x -> (x-1) `mo开发者_JS百科d` 5) 0


Because mod is defined as positive. div and mod operate on a floor basis, while / and rem do not.

Prelude> let x=(-2)
Prelude> let y=5
Prelude> (x`div`y)*y+(x`mod`y)
-2
Prelude> y*(truncate ((fromInteger x)/fromInteger y)) + (x`rem`y)
-2
Prelude> x`rem`y
-2
Prelude> x`mod`y
3
Prelude> (fromInteger x)/fromInteger y
-0.4
Prelude> x`div`y
-1

Addendum: As KennyTM rightly points out, I should have used quot, not /:

Prelude> (x`quot`y)*y+(x`rem`y)
-2
Prelude> (x`quot`y)
0

I simply did not remember it, and was too hasty to look it up. quot will do an integer division.


-1 modulo 5 is, by definition, 4.

0

精彩评论

暂无评论...
验证码 换一张
取 消