如何改进匹配模式以在 Ocaml 中提取列表的第二项

How to improve the match pattern to extract second item of a list in Ocaml

我有一个包含两个项目的列表,比如 [1;2]。我尝试通过此代码提取第二项。

let _::b::_ = [1;2] in b

编译器给出警告Warning 8: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: (_::[]|[])

虽然这很明智,但我更想知道我们如何才能做得更好。能有无预警吗?

这是 OCaml 详尽检查模式的缺点。在几乎所有情况下,它都非常有用,但在少数情况下,您希望使用一种并不详尽的模式。也就是说,在您知道可能的值在某种程度上受到限制的情况下。

如果您绝对肯定您的列表至少有 2 个元素,您可以使用 List.nth:

# List.nth [1; 2] 1;;
- : int = 2

然而,这仅适用于从列表中提取一个值,一般情况下不适用。

您可以关闭穷举警告:

# let [@warning "-8"] _ :: b :: _ = [1; 2] in b;;
- : int = 2

你可以写一个详尽的模式,这是我自己经常做的:

# match [1; 2] with
  | _ :: b :: _ -> b
  | _ -> assert false ;;
- : int = 2