为什么在自己的and函数实现中出现异常?

Eth*_*thr 3 recursion haskell boolean

我正在尝试and在Haskell中编写自己的函数。看起来像:

and' :: [Bool] -> Bool
and' (x:xs) = x && and' xs
Run Code Online (Sandbox Code Playgroud)

当我使用and' [True, True, True]它给我例外:

*** Exception: 6.hs:27:1-26: Non-exhaustive patterns in function and'
Run Code Online (Sandbox Code Playgroud)

我发现添加:and' _ = True解决了我的问题,但实际上为什么我必须添加此行?如果我的思维方式正确,函数应该返回我True && True && True,当我在ghci中使用此组合时,它会返回True。你能给我解释一下吗?有没有办法查看andghci 中函数的实现?

Wil*_*sem 13

如果我的想法是正确的,函数应该返回我True && True && True,当我使用这种组合ghci时返回True

你的and' [True, True, True]意志归结为。由于您没有为空列表编写子句,因此它将失败。如果列表中有一个,则它将永远不会真正调用,因为它将返回,但是仅包含s 的列表最终将使用空列表进行调用。True && True && True && and' []Falseand' []False && _FalseTrue

因此,您也可以通过处理空列表的情况来解决此问题:

and' :: [Bool] -> Bool
and' [] = True
and' (x:xs) = x && and' xs
Run Code Online (Sandbox Code Playgroud)

如果打开-Wincomplete-patterns警告[ghc-doc],它将列出您未实现的模式。

  • “如果您打开`-Wincomplete-patterns ......” –或者更明智地是`-Wall`。 (3认同)