我是新手Haskell
,我正在阅读Learn you a Haskell,在页面中他们将函数声明为
tell :: (Show a) => [a] -> String
tell [] = "The list is empty"
tell (x:[]) = "The list has one element: " ++ show x
tell (x:y:[]) = "The list has two elements: " ++ show x ++ " and " ++ show y
tell (x:y:_) = "This list is long. The first two elements are: " ++ show x ++ " and " ++ show y
哪个工作正常。书上说
这个函数是安全的,因为它处理空列表、单例列表、包含两个元素的列表和包含两个以上元素的列表。注意 (x:[]) 和 (x:y:[]) 可以重写为 [x] 和 [x,y] (因为它的语法糖,我们不需要括号)。我们不能用方括号重写 (x:y:_) 因为它匹配任何长度为 2 或更多的列表。
我试图通过将最后一行更改为
-- same as before
tell [x:y:_] = "This list is long. The first two elements are: " ++ show x ++ " and " ++ show y
Haskell 提出了一个非常丑陋的信息
Could not deduce (a ~ [a0])
from the context (Show a)
bound by the type signature for tell :: Show a => [a] -> String
at C:\Documents and Settings\Razor\Desktop\Other\baby.hs:(24,1)-(27,9
5)
`a' is a rigid type variable bound by
the type signature for tell :: Show a => [a] -> String
at C:\Documents and Settings\Razor\Desktop\Other\baby.hs:24:1
In the pattern: x : y : _
In the pattern: [x : y : _]
In an equation for `tell':
tell [x : y : _]
= "This list is long. The first two elements are: "
++ show x ++ " and " ++ show y
Failed, modules loaded: none.
任何人都可以解释什么是错的?根据书,我可以写成(x:[])
([x]
我确实做到了,只是为了确定),但为什么我不能tell (x:y:_)
写成tell [x:y:_]
. 我知道书给出了描述,但我真的不明白有什么问题?谁能用清晰的语言解释一下?