我刚开始学习Haskell,正在跟随书籍《Learn You a Haskell》。我遇到了以下示例:
tell :: (Show a) => [a] -> String
tell [] = "The list is empty"
我明白这里的
(Show a)
是一个类约束,而参数的类型,在这种情况下是 a
必须能够被“showable”显示。考虑到这里的
a
是一个列表而不是列表中的元素,为什么我无法声明函数如下:tell :: (Show a) =>a->String
编辑1:-从下面的答案中,我似乎理解到需要指定模式匹配的a
的具体类型。考虑到这一点,下面的实现应该是正确的:
pm :: (Show a) =>a->String
pm 'g'="wow"
它给我以下错误:
Could not deduce (a ~ Char)
from the context (Show a)
bound by the type signature for pm :: Show a => a -> String
at facto.hs:31:7-26
`a' is a rigid type variable bound by
the type signature for pm :: Show a => a -> String at facto.hs:31:7
In the pattern: 'g'
In an equation for `pm': pm 'g' = "wow"
失败了,已加载的模块: 无。
从错误信息中我理解到无法推断 a
的具体类型,但是如何使用 Show
声明呢。
我知道可以通过这种方式解决以上问题:
pmn :: Char->String
pmn 'g'="wow"
但我只是想更好地理解Show
类型类