haskell - 数据类型列表 : "could not deduce (a ~ SomeType) from the context (SomeTypeclass a)"

标签 haskell types

我对 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 是一个多态列表,其中包含满足显示约束的任何元素。但 stList 不是多态列表!它是 SampleType 的列表。因此,删除签名并查看 ghci 推断出的内容,或者直接提供正确的签名:::[SampleType]

关于haskell - 数据类型列表 : "could not deduce (a ~ SomeType) from the context (SomeTypeclass a)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5453514/

相关文章:

haskell - 声明 ToJSON 实例时出现编译错误

TypeScript 按任意类型过滤元组类型

javascript - 在水平日历上显示时间数据

c - 为什么我们不用一个短整型来表示一个返回值呢?

haskell - 'Either e` 包中 `Failure` 的 "failure"实例存在问题

linux - haskell cabal : Mysterious missing or recursive dependencies

haskell - 使用标准的类型错误

java - Java 中的不兼容类型错误

amazon-web-services - 如何在 Typescript 中优雅地导入 AWS - Lambda?

haskell - 在 GHC (Haskell) 中捕获 Control-C 异常