【问题标题】:Passing default parameters to functions as default parameters将默认参数作为默认参数传递给函数
【发布时间】:2019-12-18 19:37:16
【问题描述】:

我有许多带有默认参数的函数,例如。

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 中是可能的,还是错误的方法? 谢谢S

【问题讨论】:

    标签: ocaml conventions optional-parameters default-arguments


    【解决方案1】:

    试试这个:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多