积分运算符 quot 与 div [英] Integral operators quot vs. div

查看:23
本文介绍了积分运算符 quot 与 div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类型类 Integral 有两个操作 quotdiv,但在 Haskell 2010 语言报告中并没有指定它们应该做什么.假设div是整数除法,quot有什么不同,或者quot的目的是什么?你什么时候用一个,什么时候用另一个?

解决方案

引用 Haskell 报告中的第 6.4.2 节:

quotremdivmod 类方法满足这些法则,如果 y 是非零:

(x `quot` y)*y + (x `rem` y) == x(x `div` y)*y + (x `mod` y) == x

quot 是向零截断的整数除法,而 div 的结果向负无穷大截断.

div 函数通常使用起来更自然,而 quot 函数对应于现代机器上的机器指令,因此效率更高.>

Type class Integral has two operations quot and div, yet in the Haskell 2010 Language Report it is not specified what they're supposed to do. Assuming that div is integral division, what does quot differently, or what is the purpose of quot? When do you use one, and when the other?

解决方案

To quote section 6.4.2 from the Haskell report:

The quot, rem, div, and mod class methods satisfy these laws if y is non-zero:

(x `quot` y)*y + (x `rem` y) == x  
(x `div`  y)*y + (x `mod` y) == x

quot is integer division truncated toward zero, while the result of div is truncated toward negative infinity.

The div function is often the more natural one to use, whereas the quot function corresponds to the machine instruction on modern machines, so it's somewhat more efficient.

这篇关于积分运算符 quot 与 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆