将默认参数传递给函数作为默认参数

我有许多带有默认参数的功能,例如

let h_foo a b = a * b
let foo ?(f_heuristic=h_foo) a b = f_heuristic a b

(* caller of foo where may want to change `f_heuristic` *)
let fn ?(f=foo) a b =
  f a b

fn 5 6                                            (* => 30 *)

但是,我希望能够使用不同的默认值调用包装函数,以使用包装函数的默认值。我遇到以下错误,这使我感到困惑,而且我不知道如何解决。

fn ~f:(fun a b -> a + b) 5 6
(* Line 1,characters 6-24:
 * Error: This function should have type
 *          ?f_heuristic:(int -> int -> int) -> int -> int -> int
 *        but its first argument is not labelled *)

这在Ocaml中可行吗,还是错误的方法? 谢谢

fkpy123 回答:将默认参数传递给函数作为默认参数

尝试一下:

let fn ?(f=(foo : int -> int -> int)) a b = f a b;;

问题是代码中的可选参数f的类型被推断为具有可选参数的foo的类型。通过将默认值更改为所需的类型,您也可以为fn指定所需的类型。

本文链接:https://www.f2er.com/2896396.html

大家都在问