gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:50:12 33 4
gpt4 key购买 nike

我对 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com