Haskell无法将预期类型'Bool'与类型[t0]匹配

The*_*ake 0 haskell types ghc

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])
Run Code Online (Sandbox Code Playgroud)

错误:

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 [] [_ : __] = []
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 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
Run Code Online (Sandbox Code Playgroud)

或者我们可以将函数重写为:

nor :: Bits -> Bits -> Bits
nor (x:xs) (y:ys) = not (x || y) : nor xs ys
nor [] [] = []
nor _ _ = error "mismatched length"
Run Code Online (Sandbox Code Playgroud)

请注意,由于懒惰,如果您以take k结果为例,k小于两个列表的长度,则不会引发错误.