对于上下文,我试图创建一个简单的函数,在偶数位置输出列表的元素。
>evens [] = []
>evens [x] = x
>evens (x, y, xs) = x : evens xs
为什么这会在编译时抛出类型错误?
我将第二行更改为:
>evens [x] = x:[]
然后一切都很好。
learnyouahaskell.com指出在模式匹配中,(x:[])可以重写为[x],但为什么在我的函数定义中失败?
答案 0 :(得分:2)
[x] != x
。一个元素的列表与元素本身不同。您可以将x:[]
替换为[x]
,但不能将[x]
替换为x
!而且,你的第三个等式似乎是错的。你说它编译得很好,所以它可能是一个错字,但是,可以肯定的是,这里是evens
的完整定义:
evens :: [a] -> [a]
evens [] = []
evens [x] = [x] -- x :: a; you can't use an a where you need a [a]!
evens (x:y:xs) = x : evens xs
-- x :: a; xs :: [a]; evens xs :: [a]; (:) :: a -> [a] -> [a]
-- x : evens xs :: [a]