OCaml 中的异构集
假设我有一个定义为的类型,
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Set.Make 函子采用模块签名 Set.OrderedType :
为了进行比较,您可以使用
Pervasives.compare
如果您对min_elt
/max_elt
返回的顺序和结果没有任何要求。因此函子的参数可以很简单:Set.Make functor takes the module with signature Set.OrderedType :
For comparison you can use
Pervasives.compare
if you don't have any requirements on the order and results returned bymin_elt
/max_elt
. So the parameter to the functor can be as simple as :