OCaml 嵌套模式 - 尽管定义了模式但仍存在异常

发布于 2024-12-27 20:54:38 字数 653 浏览 3 评论 0原文

我有一个这样定义的函数:

 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悲喜皆因你 2025-01-03 20:54:38

如果我们修复代码的缩进,它看起来像这样:

let test_func lis =
  match lis with h::t ->
    match h with h2::t2 ->
      h2
    | [] ->
      []
    | [] ->
      [];;

如果你看一下,很明显第一个和第二个 | 之间没有区别。 []-> []。因此编译器无法知道您希望第二个匹配语句属于外部匹配语句而不是内部匹配语句。因此,您需要使用括号告诉编译器内部匹配语句应该在第一个 | 之后结束。 []-> []

在您的第二个版本中,第一个 | []-> [] 显然属于外部匹配语句,因为内部匹配语句直到程序的更深处才会出现。所以没有歧义,因此不需要括号。

If we fix the indentation of your code, it looks like this:

let test_func lis =
  match lis with h::t ->
    match h with h2::t2 ->
      h2
    | [] ->
      []
    | [] ->
      [];;

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文