OCaml:如何使用相同类型的 Set 参数创建归纳类型
OCaml: how to create an inductive type with Set argument of same type
在 OCaml 中我可以定义以下类型:
type mytype = Base of int
| Branch of (int * (collection -> collection))
and collection = mytype list
假设我根据每个构造函数的 int 值定义了一个比较函数,我怎样才能将 collection
转换为 Set
而不是 list
?
这是您需要使用递归模块的情况之一。事实上,您可以看到这是您在 documentation of the feature 中获得的实际示例。所以应该按照这些思路去做:
module rec Mytype : sig
type t = Base ...
val compare : t -> t -> int
end = struct
type t = Base ...
let compare v0 v1 = ...
end
and Collection : Set.S with type elt = Mytype.t
= Set.Make (Mytype)
在 OCaml 中我可以定义以下类型:
type mytype = Base of int
| Branch of (int * (collection -> collection))
and collection = mytype list
假设我根据每个构造函数的 int 值定义了一个比较函数,我怎样才能将 collection
转换为 Set
而不是 list
?
这是您需要使用递归模块的情况之一。事实上,您可以看到这是您在 documentation of the feature 中获得的实际示例。所以应该按照这些思路去做:
module rec Mytype : sig
type t = Base ...
val compare : t -> t -> int
end = struct
type t = Base ...
let compare v0 v1 = ...
end
and Collection : Set.S with type elt = Mytype.t
= Set.Make (Mytype)