为什么这种类型变量不明确?

dav*_*420 6 haskell type-inference typeclass

Cabbage.hs:

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))
Run Code Online (Sandbox Code Playgroud)

当我编译(使用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)
Run Code Online (Sandbox Code Playgroud)

我不明白为什么a暧昧.当然第a7行与a第6行相同?我该如何解决?

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

nom*_*olo 11

使用范围类型变量,您可以让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))
Run Code Online (Sandbox Code Playgroud)