OCaml:带有标签和可选参数的函数应用程序

OCaml: Function application with labelled and optional arguments

我正在编写一个函数,其中 x 作为可选参数,y,z 作为标记参数。假设格式类似于 concat1。我意识到,当我尝试执行 concat1 y:"hello" z:"world" 时,它实际上并没有应用该功能,而是 returns 一个功能。

let concat1 ?(x = " ") ~y ~z = y ^x ^ z
let concat2 ?(x = " ") y z = y ^x ^z
let concat3 ?(x = " ") y ~z = y ^ x ^z
let concat4 ?(x = " ") ~y z = 

应用这些不同形式的结果是

concat1 ~y:"hello ~z:"world" -> ?x:string -> string <fun>
concat1 "hello" "world" -> "hello world"
concat2 "hello" "world" -> "hello world"

concat3 "hello" -> z:string -> string = <fun>
concat4 "world" -> y:string -> string = <fun>

如何让 concat1 执行?我不想调用没有标记参数的函数。

这是来自 language definition 的文本:

If a non-labeled argument is passed, and its corresponding parameter is preceded by one or several optional parameters, then these parameters are defaulted, i.e. the value None will be passed for them. All other missing parameters (without corresponding argument), both optional and non-optional, will be kept, and the result of the function will still be a function of these missing parameters to the body of f.

因此,如果您希望默认可选参数,则需要至少提供一个非标记参数。由于您的 concat1 函数没有未标记的参数,因此这是不可能的。

我见过的关于带有大量标记参数和可选参数的函数的习惯用法是有一个最终单元参数:

let concat1 ?(x = " ") ~y ~z () = y ^ x ^ z

然后您可以轻松地提供一个未标记的参数来获取可选参数的默认值。

# let concat1 ?(x = " ") ~y ~z () = y ^ x ^ z;;
val concat1 : ?x:string -> y:string -> z:string -> unit -> string = <fun>
# concat1 ~y: "abc" ~z: "def" ();;
- : string = "abc def"

我不确定这是否适合你。