哈斯克尔除法
我正在 Haskell 中创建一个函数,仅将列表中的偶数减半,但我遇到了问题。当我运行编译器时,它抱怨您无法执行 int 除法,并且我需要一个小数 int 类型声明。我尝试将类型声明更改为 float,但这只是生成了另一个错误。我已在下面包含该函数的代码,并希望获得任何形式的帮助。
halfEvens :: [Int] -> [Int]
halfEvens [] = []
halfEvens (x:xs) | odd x = halfEvens xs
| otherwise = x/2:halfEvens xs
感谢您的阅读。
I'm making a function in Haskell that halves only the evens in a list and I am experiencing a problem. When I run the complier it complains that you can't perform division of an int and that I need a fractional int type declaration. I have tried changing the type declaration to float, but that just generated another error. I have included the function's code below and was hoping for any form of help.
halfEvens :: [Int] -> [Int]
halfEvens [] = []
halfEvens (x:xs) | odd x = halfEvens xs
| otherwise = x/2:halfEvens xs
Thank you for reading.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
div
,执行整数除法:(/)
函数需要类型为 Fractional 类的参数,并执行标准除法。div
函数需要类型为 Integral 类的参数,并执行整数除法。更准确地说,
div
和mod
向负无穷大舍入。它们的表兄弟quot
和rem
的行为类似于 C 中的整数除法 并向零舍入。div
和mod
在进行模算术时通常是正确的(例如,在计算给定日期的星期几时),而quot
和rem
稍微快一些(我认为)。在 GHCi 中玩一下:
Use
div
, which performs integer division:The
(/)
function requires arguments whose type is in the class Fractional, and performs standard division. Thediv
function requires arguments whose type is in the class Integral, and performs integer division.More precisely,
div
andmod
round toward negative infinity. Their cousins,quot
andrem
, behave like integer division in C and round toward zero.div
andmod
are usually correct when doing modular arithmetic (e.g. when calculating the day of the week given a date), whilequot
andrem
are slightly faster (I think).Playing around a bit in GHCi:
我应该补充一点,使用
map
会简化代码。I should add that using
map
would simplify the code.