gpt4 book ai didi

compare - 变体的结构比较

转载 作者:行者123 更新时间:2023-12-02 21:08:07 26 4
gpt4 key购买 nike

我想处理整数行上的限制。我想要Pervasives.compare对待RightInfinity > Point x 表示所有 x,而 LeftInfinity 则相反。 .

ocaml回复:

# 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]

但是

# 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"

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

可以依赖类型声明中变体出现的顺序与标记的顺序之间的任何关系吗?

最佳答案

不,你不应该依赖它。您应该定义自己的比较函数。当然,这意味着您必须通过数据结构来提升它(例如,能够比较 open_pt 列表),但当您想要进行特定于域的比较时,这是安全的做法功能。

请注意,扩展标准库(例如 Batteries 或 Core)提供了辅助函数来提升所有常见数据结构的比较,从而帮助您将特定于域的比较扩展到包含 open_pt 的任何类型。

编辑:请注意,您可以依赖它,因为非常量构造函数的顺序是 specified in the OCaml/C interface 。不过,我认为这不是一个好主意——如果下次您需要将闭包放入仿函数参数类型中怎么办?

关于compare - 变体的结构比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17116858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com