OCaml 嵌套模式 - 尽管定义了模式但仍存在异常
我有一个这样定义的函数:
let test_func lis =
match lis with h::t ->
match h with h2::t2 ->
h2
| [] ->
[]
| [] ->
[];;
编译时,我收到一条警告,指出该函数与模式 [] 不匹配 - 即使我将其定义为第二种情况!我发现我可以通过用括号包围第二个匹配语句来解决这个问题:
let test_func lis =
match lis with h::t ->
(match h with h2::t2 ->
h2
| [] ->
[])
| [] ->
[];;
但我想知道为什么这是必要的。此外,交换顶级匹配语句中的第一个和第二个案例也有效:
let test_func lis =
match lis with [] ->
[]
| h::t ->
match h with h2::t2 ->
h2
| [] ->
[];;
谢谢!
I have a function defined like this:
let test_func lis =
match lis with h::t ->
match h with h2::t2 ->
h2
| [] ->
[]
| [] ->
[];;
When compiled, I get a warning that this function does not match the pattern [] - even though I defined it as the second case! I have found that I can fix this by surrounding the second match statement with parens:
let test_func lis =
match lis with h::t ->
(match h with h2::t2 ->
h2
| [] ->
[])
| [] ->
[];;
but I was wondering why this is necessary. In addition, swapping the first and second case in the top level match statement also works:
let test_func lis =
match lis with [] ->
[]
| h::t ->
match h with h2::t2 ->
h2
| [] ->
[];;
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我们修复代码的缩进,它看起来像这样:
如果你看一下,很明显第一个和第二个
| 之间没有区别。 []-> []
。因此编译器无法知道您希望第二个匹配语句属于外部匹配语句而不是内部匹配语句。因此,您需要使用括号告诉编译器内部匹配语句应该在第一个| 之后结束。 []-> []
。在您的第二个版本中,第一个
| []-> []
显然属于外部匹配语句,因为内部匹配语句直到程序的更深处才会出现。所以没有歧义,因此不需要括号。If we fix the indentation of your code, it looks like this:
If you look at that, it becomes obvious that there's no difference between the first and the second
| [] -> []
. So the compiler has no way of knowing that you intended the second one to belong to the outer match-statement and not to the inner one. Thus you need to parentheses to tell the compiler that the inner match statement should end after the first| [] -> []
.In your second version the first
| [] -> []
clearly belongs to the outer match-statement because the inner match-statement doesn't even appear until farther down in the program. So there's no ambiguity and thus no need for parentheses.