【发布时间】:2013-08-10 17:54:17
【问题描述】:
我是 Haskell 的新手,我正在尝试编写一个接受列表并返回布尔值的函数。
如果它的输入列表是只包含'a'的列表,它将返回True,否则返回False。
这是我的最佳猜测:
f :: [a] -> Bool
f ('a':[]) = True
f (x:xs) = False
编译失败,返回:
Couldn't match type `a' with `Char'
`a' is a rigid type variable bound by
the type signature for f :: [a] -> Bool at charf.hs:6:1
In the pattern: 'b'
In the pattern: 'b' : []
In an equation for `f': f ('b' : []) = True
我的逻辑有什么错误?
【问题讨论】:
-
你的意思是列表应该只包含一个
Char'a'吗?在这种情况下,您的函数应该具有类型[Char] -> Bool。目前签名允许任何类型的列表,这就是您收到错误的原因。 -
请注意,您可以简单地使用
f x = x=="a",或者更简洁地使用f = (=="a")。