多态默认函数参数

Polymorphic default function argument

有没有办法避免像下面这样重写函数以应用于多种类型?

在这个例子中,我可以这样写可选函数 f_comp 以避免写两个函数的必要性吗?

示例:

module M = Map.Make (String)
module S = Set.Make (String)
let m = M.add "a" (S.of_list ["a"; "b"]) M.empty
      |> M.add "b" (S.of_list ["a"])

let h_highest_degree ?(f_comp=(>)) a b g : bool =
  f_comp (S.cardinal (M.find a g)) (S.cardinal (M.find b g))

(* Can I avoid need to define this function? *)
let h_highest_degree_f ?(f_comp=(>)) a b g =
  f_comp (float_of_int (S.cardinal (M.find a g)))
    (float_of_int (S.cardinal (M.find b g)))

(* e.g *)
h_highest_degree "a" "b" m

除了默认函数外,它们对我来说似乎都具有相同的类型签名。

这是您可以为 h_highest_degree_f 给出的替代定义,它不会像 h_highest_degree:

的定义那样重复
let h_highest_degree_f ?(f_comp=(>)) a b g =
  h_highest_degree a b g
    ~f_comp:(fun x y -> f_comp (float_of_int x) (float_of_int y))

(* h_highest_degree_f : ?f_comp:(float -> float -> bool) -> string -> string -> S.t M.t -> bool *)

不过,我不太确定这是否是您要问的。您说您正在寻找 "avoid rewriting functions like the following to apply to multiple types." 的方法,但是您的程序中没有在多种类型上使用的函数。 h_highest_degree 中的 f_comp 具有 int -> int -> bool 类型(因为 S.cardinal (M.find a g)S.cardinal (M.find b g) 都具有 int 类型,而 return 类型该函数被显式注释为类型 bool)。由于 S.cardinal (M.find a g)S.cardinal (M.find b g) 被硬连接到您对 h_highest_degree 的定义中,我不确定 f_comp 怎么可能有除 int -> int -> bool 之外的任何类型。如果我的回答没有回答您的问题,您能否再举一个例子说明您要完成的工作?