卷心菜

module Cabbage where
class Cabbage a
  where foo :: a -> String      -- the parameter is only present for its type,
                                -- the parameter value will be ignored
        bar :: String -> a
quux :: Cabbage a => String -> a
quux s = bar (s ++ foo (undefined :: a))

当我使用ghc编译时,出现以下错误消息:
Cabbage.hs:7:19:
    Ambiguous type variable `a' in the constraint:
      `Cabbage a' arising from a use of `foo' at Cabbage.hs:7:19-38
    Probable fix: add a type signature that fixes these type variable(s)

我不明白a为什么模棱两可。当然,第7行中的a与第6行中的a相同吗?我该如何解决?

或者,是否有更好的方法来声明每个实例的常量?

最佳答案

使用作用域类型变量,您可以让GHC知道undefined :: a应该是相同的(否则a只是forall a. a的简写)。然后必须明确限定范围的类型变量为全限定的:

{-# LANGUAGE ScopedTypeVariables #-}
module Cabbage where
class Cabbage a
  where foo :: a -> String      -- the parameter is only present for its type,
                                -- the parameter value will be ignored
        bar :: String -> a
quux :: forall a. Cabbage a => String -> a
quux s = bar (s ++ foo (undefined :: a))

09-25 20:58