在 OCaml 中,如何在保留变量名称的同时模式匹配函数参数

in OCaml how can I pattern match a function argument while keeping the variable name

我有一些代码:

let some_func some_arg = (* ... *)

其中 some_arg 确实需要 [| arg1; arg2 |]。我想在函数参数位置进行模式匹配,例如:

let some_func [| arg1; arg2 |] = (* ... *)

但我也想保留变量名 some_arg 以防我想直接用它做一些事情。我该怎么做?

函数参数是模式,因此您可以使用 as 构造来命名部分(或全部)模式:

let some_func ([| arg1; arg2 |] as some_arg) = (* . . . *)

但是这个模式并不详尽,因为它只匹配长度为 2 的数组。所以它是一个脆弱的函数定义,您会收到编译器的警告。

只使用 match 可能会更好,这样当数组的长度不是 2 时,您可以指定所需的行为。或者您可以使用始终恰好有 2 个组件的类型(例如一个元组)。