作者:勿缘无悔 | 来源:互联网 | 2022-12-07 02:20
haskell新手,当我尝试模式匹配非空列表时,我一直遇到这个神秘的错误
码:
type Bits = [Bool]
nor :: Bits -> Bits -> Bits
nor [] [_:__] = error "mismatched length"
nor [_:__] [] = error "mismatched length"
nor [] [] = []
nor (x:xs) (y:ys) = (norBit x y):nor xs ys
where norBit x y = if x == True || y == True then False else True
main = do
print (nor [True] [False])
错误:
gates.hs:4:9:
Couldn't match expected type ‘Bool’ with actual type ‘[t0]’
In the pattern: _ : __
In the pattern: [_ : __]
In an equation for ‘nor’: nor [] [_ : __] = []
Willem Van O..
5
在Haskell列表构造函数[]
和(x:xs)
,注意第二个构造采用圆形支架.
如果你写[_:__]
,那么这也是有效的语法:因为Haskell认为你写了一个模式[(x:xs)]
,所以是一个单例列表,第一个元素匹配(x:xs)
模式.但是,这应该意味着类型为[[a]]
,而不是一个[a]
,并且因为Bool
是不是一个列表类型的类型别名,这个问题不能得到解决.
您可以通过编写圆括号来解决此问题:
nor :: Bits -> Bits -> Bits
nor [] (_:_) = error "mismatched length"
nor (_:_) [] = error "mismatched length"
nor [] [] = []
nor (x:xs) (y:ys) = (norBit x y):nor xs ys
where norBit x y = if x == True || y == True then False else True
或者我们可以将函数重写为:
nor :: Bits -> Bits -> Bits
nor (x:xs) (y:ys) = not (x || y) : nor xs ys
nor [] [] = []
nor _ _ = error "mismatched length"
请注意,由于懒惰,如果您以take k
结果为例,k
小于两个列表的长度,则不会引发错误.
1> Willem Van O..:
在Haskell列表构造函数[]
和(x:xs)
,注意第二个构造采用圆形支架.
如果你写[_:__]
,那么这也是有效的语法:因为Haskell认为你写了一个模式[(x:xs)]
,所以是一个单例列表,第一个元素匹配(x:xs)
模式.但是,这应该意味着类型为[[a]]
,而不是一个[a]
,并且因为Bool
是不是一个列表类型的类型别名,这个问题不能得到解决.
您可以通过编写圆括号来解决此问题:
nor :: Bits -> Bits -> Bits
nor [] (_:_) = error "mismatched length"
nor (_:_) [] = error "mismatched length"
nor [] [] = []
nor (x:xs) (y:ys) = (norBit x y):nor xs ys
where norBit x y = if x == True || y == True then False else True
或者我们可以将函数重写为:
nor :: Bits -> Bits -> Bits
nor (x:xs) (y:ys) = not (x || y) : nor xs ys
nor [] [] = []
nor _ _ = error "mismatched length"
请注意,由于懒惰,如果您以take k
结果为例,k
小于两个列表的长度,则不会引发错误.