在 OCaml 中匹配“*”

Match "*" in OCaml

在我的 OCaml 程序中,我有以下内容:

let rec string_of_list p "" = match p with  
[] -> "[]"
|s::rest -> String.concat " " [Bytes.to_string s; string_of_list rest ""]

这段代码嵌套在更多代码中,但是编译时出现错误:

Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
"*"

星星是指 Kleene 外壳吗?我尝试通过附加以下匹配项来解决问题:

| _ -> "ERROR"

但我仍然遇到同样的错误。有人可以帮我吗?

没关系,问题出在函数定义上:

let rec string_of_list p "" = match p with 

引号不应该出现在那里。不过我还是很好奇 * 代表什么。

编译器告诉您,您写成 "" 的参数并不匹配调用者可以传递给函数的所有可能的字符串。也就是说,它并不详尽。

为了获得额外帮助,编译器选择了一个不匹配的字符串来说明问题。它选择字符串 "*" 有点奇怪,但这确实是一个不匹配的字符串。

这是一个非常简单的会话,完全显示了相同的问题:

        OCaml version 4.02.1

# let f "" = 44;;
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
"*"
val f : string -> int = <fun>
# 

实际上,如果将 "*" 传递给 f,它将失败(因为其参数由非穷尽模式指定):

#  f "*";;
Exception: Match_failure ("//toplevel//", 1, 6).

这就是编译器告诉你的。有一些参数会导致这个异常。 (实际上除空字符串以外的所有参数都会导致异常)。

我不知道为什么编译器在所有可能的字符串中选择 "*" 来提及。

(注意OCaml中的函数参数由patterns指定,而""是匹配空字符串的有效模式。所以函数f 这是一个完全有效的函数,当传递空字符串时 returns 44 并为所有其他字符串引发异常。)

您正在隐式匹配一个已弃用的字符串。

查看以下两期了解更多信息

  1. https://github.com/ocaml/ocaml/pull/250
  2. https://github.com/ocaml/ocaml-manual/pull/13