[英]Haskell, a simple pattern matching gets error
let countList (x:xs) = 1+countList xs
let countList [] = 0
countList [1,2,3]
*** Exception: <interactive>:35:5-20: Non-exhaustive patterns in function countList
I think that's too simple to get an error, but an error is still there I'm shocked 我认为这样做太简单了,但是错误仍然存在,我感到震惊
Using multiple let
statements means you're really defining two functions, with the second definition shadowing the first one. 使用多个
let
语句意味着你真正定义了两个函数,第二个定义遮蔽了第一个函数。 Thus, countList [1, 2, 3]
throws an exception because the definition that's in scope is only defined for []
. 因此,
countList [1, 2, 3]
抛出异常,因为范围内的定义仅为[]
定义。
You need to define both equations at the same time with a single let
. 您需要使用单个
let
同时定义两个方程式。 You can either type them on one line, separating the cases with a semicolon 您可以在一行上键入它们,用分号分隔案例
> let countList (x:xs) = 1 + countList xs; countList [] = 0
or use GHCi's multiline syntax :{ ... :}
, making sure to align the second countList
with the first one. 或者使用GHCi的多行语法
:{ ... :}
,确保将第二个countList
与第一个对齐。
> :{
| let countList (x:xs) = 1 + countList xs
| countList [] = 0
| :}
I guess you're working in GHCi. 我想你在GHCi工作。 The problem with your code is that you're not defining two cases of a pattern match on a single function, but that you're just redefining the function itself.
您的代码的问题在于您没有在单个函数上定义两种模式匹配的情况,而是您只是重新定义函数本身。 Thus you get the
let countList (x:xs) = 1+countList xs
part replaced by let countList [] = 0
, which is in fact a non-exhaustive pattern-match. 因此,您将
let countList (x:xs) = 1+countList xs
部分替换为let countList [] = 0
,这实际上是非详尽的模式匹配。
You're redefining countList
function instead of extending the existing definition with more pattern guards. 您正在重新定义
countList
函数,而不是使用更多模式保护扩展现有定义。 I'm not sure if there is a way to do what you want to do, in GHCi(other than using case ... of ...
expressions). 我不确定在GHCi中是否有办法做你想做的事情(除了使用
case ... of ...
表达式的情况)。
See also this: GHCi "let" -- what does it do? 另见: GHCi“让” - 它做什么?
Do you have to use let? 你必须使用let吗?
If not, this is simplest. 如果没有,这是最简单的。
countList [] = 0
countList (x:xs) = 1 + countList xs
The condition for 0 should be before the generic condition. 0的条件应该在通用条件之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.