变体的结构比较 [英] structural comparison of variants

查看:90
本文介绍了变体的结构比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想处理整数行的限制。
我想要 Pervasives.compare 处理 RightInfinity > x 的所有 x ,以及 LeftInfinity b

ocaml REPL:

  #type open_pt = LeftInfinity | Point of int | RightInfinity 
;;
#List.sort Pervasives.compare [LeftInfinity;点0;点1; RightInfinity]
;;
- :open_pt list = [LeftInfinity; RightInfinity;点0; Point 1]

 #type open_pt = LeftInfinity | Point of int |单位的RightInfinity 
;;
#List.sort Pervasives.compare [LeftInfinity;点0;点1; RightInfinity()]
;;
- :open_pt list = [LeftInfinity;点0;点1; RightInfinity()]

多态比较的危险



可以依赖于订单之间的任何关系其中变量出现在类型声明和标签的顺序?

解决方案

不,你不应该依赖。你应该定义自己的比较函数。当然,这意味着你必须通过数据结构(以便能够比较,例如, open_pt 的列表),但这是安全的事情,当你做需要一个域特定的比较函数。



请注意,扩展标准库,如Batteries或Core提供辅助功能,以提升比较通过所有常见的数据结构,与包含 open_pt 的任何类型的特定比较。



编辑:请注意,您可以 >依赖于,因为非常量构造函数的排序是指定的在OCaml / C接口。我不认为这是一个好主意,但是 - 如果你需要下一次把闭包放在你的函数参数类型中?


I want to deal with limits on the integer number line. I would like to have Pervasives.compare treat RightInfinity > Point x for all x, and the inverse for LeftInfinity.

In the ocaml REPL:

# type open_pt = LeftInfinity | Point of int | RightInfinity
  ;;
# List.sort Pervasives.compare [LeftInfinity; Point 0; Point 1; RightInfinity]
  ;;
- : open_pt list = [LeftInfinity; RightInfinity; Point 0; Point 1]

but

# type open_pt = LeftInfinity | Point of int | RightInfinity of unit
  ;;
# List.sort Pervasives.compare [LeftInfinity; Point 0; Point 1; RightInfinity ()]
  ;;
- : open_pt list = [LeftInfinity; Point 0; Point 1; RightInfinity ()]

"The perils of polymorphic compare" says

Variants are compared first by their tags, and then, if the tags are equal, descending recursively to the content.

Can one rely on any relationship between the order in which variants appear in a type declaration and the order of the tags?

解决方案

No, you should not rely on that. You should define your own comparison function. Of course, that means you'll have to lift it through datastructures (to be able to compare, say, lists of open_pt), but that's the safe thing to do when you want a domain-specific comparison function.

Note that extended standard libraries such as Batteries or Core provide auxiliary functions to lift comparisons through all common datastructures, to help you extend your domain-specific comparison to any type containing an open_pt.

Edit: Note that you can rely on that, as the ordering of non-constant constructors is specified in the OCaml/C interface. I don't think that's a good idea, though -- what if you need to put closures inside your functor argument type next time?

这篇关于变体的结构比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆