比较适用于所有类型吗? [英] Does compare work for all types?

查看:83
本文介绍了比较适用于所有类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑类型t和两个变量x,y类型t.

Let's consider a type t and two variables x,y of type t.

呼叫compare x y是否对任何类型的t有效?我找不到任何反例.

Will the call compare x y be valid for any type t? I couldn't find any counterexample.

推荐答案

多态的 compare 函数通过递归地探究值的结构,对OCaml值提供临时的总排序,以用于定义由多态 = 运算符测试的结构相等性.

The polymorphic compare function works by recursively exploring the structure of values, providing an ad-hoc total ordering on OCaml values, used to define structural equality tested by the polymorphic = operator.

从设计上看,@ antron并未对函数和闭包进行定义.该定义的递归性质意味着未在包含函数或闭包的值上定义结构相等性.这种递归性质还暗示 compare 函数未在递归值上定义,就像@antron也提到的那样.

It is, by design, not defined on functions and closures, as observed by @antron. The recursive nature of the definition implies that structural equality is not defined on values containing a function or a closure. This recursive nature also imply that the compare function is not defined on recursive values, as mentioned by a @antron as well.

结构相等性,因此 compare 函数和比较运算符,不了解结构不变性,因此不能用于(温和地)比较高级数据结构,如Sets,Maps,HashTbls等在.如果需要比较这些结构,则必须编写专门的函数,这就是Set和Map定义此类函数的原因.

Structural equality, and therefore the compare function and the comparison operators, is not aware of structure invariants and cannot be used to compare (mildly) advanced data structures such as Sets, Maps, HashTbls and so on. If comparison of these structures is desired, a specialised function has to be written, this is why Set and Map define such a function.

定义自己的结构时,最好的经验法则是区分它们

When defining your own structures, a good rule of thumb is to distinguish between

  • 具体类型,仅根据基本类型和其他具体类型定义.具体类型不应该用于其处理需要一些不变量的结构,因为创建这种类型的任意值很容易打破这些不变量.对于这些类型,多态比较函数和运算符是合适的.

  • concrete types, which are defined only in terms of primitive types and other concrete types. Concrete types should not be used for structures whose processing expects some invariants, because it is easy to create arbitrary values of this type breaking these invariants. For these types, the polymorphic comparison function and operators are appropriate.

抽象类型,其具体定义已隐藏.对于这些类型,最好提供专门的比较功能. 混合物库定义了自述文件.

abstract types, whose concrete definition is hidden. For these types, it is best to provide specialised comparison function. The mixture library defines a compare mixin that can be used to derive comparison operators from the implementation of a specialised compare function. Its use is illustrated in the README.

这篇关于比较适用于所有类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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