数据类型列表:“不能从上下文(SomeTypeclass a)推导出(a〜SomeType)” [英] Lists of data types: "could not deduce (a ~ SomeType) from the context (SomeTypeclass a)"
问题描述
Haskell的类型系统有以下问题:我试图声明一个数据类型并从函数返回一个包含此类型元素的列表。不幸的是,即使是最小的测试用例,比如
I have the following problem with Haskell's type system: I am trying to declare a data type and return a list containing elements of this type from a function. Unfortunately, even a minimal testcase such as
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的错误消息:
fails with the following error message from both ghc-7.0.2 and 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)=> [α]
。你声明stList是一个多态列表,它包含满足show约束的任何元素。但stList不是一个多态的列表!它是 SampleType
s的列表。因此,请删除签名并查看ghci推断的内容,或者仅给它正确的签名: :: [SampleType]
。
the offending line is stList :: (Show a) => [a]
. You're declaring that stList is a polymorphic list that holds any element which satisfies the show constraint. But stList isn't a polymorphic list! It's a list of SampleType
s. So remove the signature and see what ghci infers, or just give it the correct signature: :: [SampleType]
.
这篇关于数据类型列表:“不能从上下文(SomeTypeclass a)推导出(a〜SomeType)”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!