如何在 OCaml 中同时匹配一个模式和它的一部分?

How to match a pattern and a part of it at the same time in OCaml?

我正在做一个练习,要求我比较列表的第一个和第二个元素,然后我需要在尾部进行递归调用。

如果我使用 h::t 则我无法访问第二个元素,而使用 first::second::t 则更难访问原始尾部。

有什么语法可以同时匹配两者吗?

您可以使用 as 将模式或其一部分绑定到变量,这称为 别名模式 ,供参考,这在章节 7. Patterns of the manual (https://ocaml.org/manual/)

* match [0;1;2] with 
| x::(y::t as s) -> (x,y,t,s) 
| _ -> failwith "no";

- : int * int * int list * int list = (0, 1, [2], [1; 2])