【发布时间】:2013-06-19 15:41:05
【问题描述】:
我刚刚开始学习 Haskell,并且正在关注“Learnyouahaskell”一书。我遇到了这个例子
tell :: (Show a) => [a] -> String
tell [] = "The list is empty"
我知道(Show a) 这里是一个类约束和参数类型,在这种情况下a 必须能够“显示”。
考虑到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 类型类
【问题讨论】:
-
当前标题没问题。
标签: haskell