haskell - 传递输出小数作为参数的函数时出错,但直接传递浮点数时出错
问题描述
我正在尝试编写一个接受数字和列表的函数,如果列表中的最大数字和输入数字可整除,则返回结果加 1,但如果不可整除则返回结果的上限
我的代码如下:
maxDiv n xs
| maximum xs `mod` n == 0 = ((maximum xs `div` n) + 1)
| otherwise = ceiling (1.8)
问题是当我将 1.8 替换为
((maximum xs) / n)
我收到一个错误,我将在下面发布。我试过将它放入一个单独的命名函数中,以及将它与天花板部分一起放入一个单独的函数中,例如
helper n xs = ceiling ((maximum xs) / n)
length' n xs | maximum xs `mod` n == 0 = ((maximum xs `div` n) + 1) | otherwise = helper n xs
但我仍然得到同样的错误。
• Ambiguous type variable ‘a0’ arising from a use of ‘print’
prevents the constraint ‘(Show a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance (Show b, Show a) => Show (Either a b)
-- Defined in ‘Data.Either’
instance Show Ordering -- Defined in ‘GHC.Show’
instance Show Integer -- Defined in ‘GHC.Show’
...plus 23 others
...plus 43 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In a stmt of an interactive GHCi command: print it
我看过打字,它们似乎都是小数,我做错了什么/有什么办法解决这个问题?
解决方案
你在这里混合了“ Integral
”世界和“ Fractional
”世界。实际上,div :: Integral a => a -> a -> a
andmod :: Integral a => a -> a -> a
使用的是类型Integral
,而(/) :: Fractional a => a -> a -> a
使用的是属于 typeclass 成员的类型的项目Fractional
。
虽然,严格来说,可以在 Haskell 中创建一个既是Integral
,又是 的类型,但这Fractional
两个世界并没有太多共同点。此外,无论如何我们都不需要。如果要计算 的上限a/b
,可以使用 计算div (a+b-1) b
。我们甚至可以div (a+b) b
在这里使用,因为您想添加+1
它是否可除:
maxDiv :: (Integral a, Foldable t) => a -> t a -> a
maxDiv n xs = div (maximum xs + n) n
推荐阅读
- python - 我的第一个 Python Scrapy 无法工作
- c++ - 中缀后缀转换 c++,似乎无法得到正确答案
- android - 我可以为在 Android Play Store 和 Android TV Store 中注册的应用程序使用不同的名称吗?
- javascript - 试图在 x 行上打印所有月份
- mysql - 与 MySQL 中的 case 类似,不使用 OR 或 Union
- ruby-on-rails - Rails 5.2.0 —— 如何删除cookies的子值?
- hangouts-chat - 带有个人 gmail 帐户的环聊聊天 API
- c# - 服务定位器反模式可以进行工厂注册
- android - 禁用分屏 - 显示“全屏显示”
- android - Android recyclerview 的项目动画