OCaml 中的异构集

发布于 2024-09-09 00:02:37 字数 653 浏览 1 评论 0原文

假设我有一个定义为的类型,

type value =
      None
    | Int of int
    | Float of float
    | Complex of Complex.t
    | String of string
    | Char of char
    | Bool of bool

并且我希望能够使用这些值的Sets。据我了解,我必须使用函子来具体化具有具体类型及其关联顺序的 Set 模块。

在这个例子中我应该怎么做?既然 value 不能直接在 Set.Make 函子中使用?

当然,我需要能够对这些值进行完整排序,因此我应该发明一些东西,例如为不同类型提供预定义的顺序,然后按其有效值对它们进行排序..我对吗?

例如,我可以决定使用 Int of int Int of int Int of int Int of int < int 的浮点型Int x 如果 x ,则 Int y y 。这是实现我想要实现的目标的实用方法吗?

suppose I have a type defined as

type value =
      None
    | Int of int
    | Float of float
    | Complex of Complex.t
    | String of string
    | Char of char
    | Bool of bool

and I want to be able to work with Sets of these values. From what I understood I have to use the functor to concretize the Set module with a concrete type and its associated ordering.

How should I do it in this example? Since value cannot be used directly inside the Set.Make functor?

Then of course I need to be able to give a full ordering of these values so I should invent something like giving a predefined order to different types, and then ordering them by their effective value.. am I right?

So for example I can decide to have Int of int < Float of int and Int x < Int y if x < y. Is it a practical approach to what I'm trying to achieve?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花开浅夏 2024-09-16 00:02:38

Set.Make 函子采用模块签名 Set.OrderedType

module type OrderedType = sig type t val compare : t -> t -> int end

为了进行比较,您可以使用 Pervasives.compare 如果您对min_elt/max_elt返回的顺序和结果没有任何要求。因此函子的参数可以很简单:

module T = struct type t = value let compare = compare end

Set.Make functor takes the module with signature Set.OrderedType :

module type OrderedType = sig type t val compare : t -> t -> int end

For comparison you can use Pervasives.compare if you don't have any requirements on the order and results returned by min_elt/max_elt. So the parameter to the functor can be as simple as :

module T = struct type t = value let compare = compare end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文