haskell - 为什么调用以 IO() 作为返回值的函数会导致模棱两可的类型错误?
问题描述
我有这两个函数,我的第一个函数调用第二个函数。第一个仅作为kickstarter。可悲的是,我收到以下错误。
runTo100 = rollDice 0 0
rollDice :: (Ord t, Show a, Random t, Num a, Num t) => t -> a -> IO ()
rollDice amount n = do
gen <- newStdGen
if amount <= 100
then do
let rolled = dice gen
rollDice (amount + rolled) (n + 1)
else do
putStrLn ("Rolls needed to reach 100: " ++ show n)
dice :: (Random a, RandomGen g, Num a) => g -> a
dice gen = head (take 1 $ randomRs (1, 6) gen)
错误:
Ambiguous type variable ‘t0’ arising from a use of ‘rollDice’
prevents the constraint ‘(Ord t0)’ from being solved.
Probable fix: use a type annotation to specify what ‘t0’ should be.
These potential instances exist:
instance (Ord a, Ord b) => Ord (Either a b)
-- Defined in ‘Data.Either’
instance Ord Ordering -- Defined in ‘GHC.Classes’
instance Ord Integer
-- Defined in ‘integer-gmp-1.0.2.0:GHC.Integer.Type’
...plus 23 others
...plus 89 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the expression: rollDice 0 0
In an equation for ‘runTo100’: runTo100 = rollDice 0 0
|
119 | runTo100 = rollDice 0 0 | ^^^^^^^^^^^^
为什么这会导致模棱两可的类型错误。我知道我必须在某处指定一个类型,但我是 haskell 的新手,我不完全理解发生了什么。我查看了各种帖子,但找不到任何对我有帮助的帖子。
预先感谢您的任何帮助。:)
解决方案
您的代码的问题是 GHC 可以找到许多可用于t
. 它必须是Ord
,Random
和的一个实例Num
。不幸的是,有很多类型符合要求。事实上,大多数情况Num
也是Random
和Ord
(Complex
可能是唯一的例外)。
在这一点上,GHC 要么不得不猜测,要么认输。让编译器猜测您的意思通常被认为是一件坏事,因此它会报告问题。
当你遇到这样的错误时,你需要在代码中的某个地方找到你想要使用的确切类型。通常,这应该在调用堆栈上尽可能远,在这种情况下是rollDice
.
推荐阅读
- ubuntu - 如何将 ssh 指向配置文件
- javascript - 在 React 中调用 API 的 httpRequest 的正确位置在哪里?
- r - 面板数据描述
- java - 如何在具有接口返回类型的方法中实现错误处理
- html - 对齐响应式 DIV 的内容
- python - 为什么 try: except: 不适用于 python Wikipedia API 的特定代码行?
- sql - 在插入另一个表之前验证是否存在
- apache-spark - Spark *Structured* Streaming 中的 RecordTooLargeException
- java - Android - 实时数据库多子查询?
- firebase - 检查用户位置是否在颤动中的 2 个地理点的区域内