Haskell的类型系统存在以下问题:我试图声明数据类型并从函数返回包含此类型元素的列表。不幸的是,即使是最小的测试用例,例如

data SampleType = SampleTypeConstructor

instance Show SampleType where
    show x = "(SampleType)"

stList :: (Show a) => [a]
stList = [(SampleTypeConstructor)]

main = do {
    putStrLn (show stList)
}

从ghc-7.0.2和ghc-7.1.20110327发出以下错误消息失败:
tcase.hs:7:12:
    Could not deduce (a ~ SampleType)
    from the context (Show a)
      bound by the type signature for stList :: Show a => [a]
      at tcase.hs:7:1-34
      `a' is a rigid type variable bound by
          the type signature for stList :: Show a => [a] at tcase.hs:7:1
    In the expression: (SampleTypeConstructor)
    In the expression: [(SampleTypeConstructor)]
    In an equation for `stList': stList = [(SampleTypeConstructor)]

最佳答案

冒犯的行是stList :: (Show a) => [a]。您要声明stList是一个多态列表,其中包含满足show约束的任何元素。但是stList不是多态列表!这是SampleType的列表。因此,删除签名并查看ghci会推断出什么,或者只是给它正确的签名::: [SampleType]

09-25 18:18