如何在ocaml中混合多态函数和函子?
我有一个函子从一个可比较的模块中生成一个堆模块,还有一个多态函数将Prim算法应用于具有任意标签的图。理想情况下,我希望能够写出以下内容:如何在ocaml中混合多态函数和函子?,ocaml,functor,Ocaml,Functor,我有一个函子从一个可比较的模块中生成一个堆模块,还有一个多态函数将Prim算法应用于具有任意标签的图。理想情况下,我希望能够写出以下内容: let prim (graph: 'a graph)= let module EdgeHeap=Heap.Make( struct type t='a edge ... end ) in ... let heap=EdgeHeap.create () in
let prim (graph: 'a graph)=
let module EdgeHeap=Heap.Make(
struct
type t='a edge
...
end
) in
...
let heap=EdgeHeap.create () in
...
module type GraphSpec = sig
type t
...
end
module GraphAlgorithms(G: GraphSpec) = struct
type graph = ...
module EdgeHeap = Heap.Make(struct
type t = G.t edge
...
end)
let prim (g: graph) = ...
let kruskal (g: graph) = ...
end
但ocamlc说,“a是不受约束的。如何解决此问题?通常,在图模块签名上参数化的函子中有
prim
(以及相关函数)。例如:
let prim (graph: 'a graph)=
let module EdgeHeap=Heap.Make(
struct
type t='a edge
...
end
) in
...
let heap=EdgeHeap.create () in
...
module type GraphSpec = sig
type t
...
end
module GraphAlgorithms(G: GraphSpec) = struct
type graph = ...
module EdgeHeap = Heap.Make(struct
type t = G.t edge
...
end)
let prim (g: graph) = ...
let kruskal (g: graph) = ...
end
这避免了使用类型变量;而是通过graphsec
functor参数传递类型
但是,如果您只需要将其用于单个函数,那么这可能会有些过分。然后,您可以使用。下面是一个简单的例子来说明其工作原理:
let min_list (type u) (l: u list) =
let module S = Set.Make(struct
type t = u
let compare = compare
end) in
S.of_list l |> S.min_elt