首页 > 解决方案 > 为什么调用以 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 的新手,我不完全理解发生了什么。我查看了各种帖子,但找不到任何对我有帮助的帖子。

预先感谢您的任何帮助。:)

标签: haskell

解决方案


您的代码的问题是 GHC 可以找到许多可用于t. 它必须是Ord,Random和的一个实例Num。不幸的是,有很多类型符合要求。事实上,大多数情况Num也是RandomOrdComplex可能是唯一的例外)。

在这一点上,GHC 要么不得不猜测,要么认输。让编译器猜测您的意思通常被认为是一件坏事,因此它会报告问题。

当你遇到这样的错误时,你需要在代码中的某个地方找到你想要使用的确切类型。通常,这应该在调用堆栈上尽可能远,在这种情况下是rollDice.


推荐阅读