gpt4 book ai didi

compare - 比较可以返回 -1、0 和 1 以外的任何值吗?

转载 作者:行者123 更新时间:2023-12-04 16:58:30 25 4
gpt4 key购买 nike

docs for the Pervasives.compare function声明

compare x y returns 0 if x is equal to y, a negative integer if x is less than y, and a positive integer if x is greater than y.



这表明它可以返回任何负整数或正整数,而不仅仅是 -11 , 代表更大或更小。然而, 这真的发生了吗 ?

这将使编写代码像
match String.compare key new_key with
| 1 -> Node (left, insert new_key right, key)
| -1 -> Node (insert new_key left, right, key)
| _ -> Node (left, right, key)

困难得多(使用 when ,可能?)。

我对 String.compare 特别感兴趣.看看 its implementation ,它只是转发到 Pervasives.compare ,而这又是使用 external 本地实现的.不知道它有什么作用。

最佳答案

你自己的回答表明在当前实现中不能返回其他值。不过,我会非常小心地依赖它。只要compare没有记录为三值,OCaml 的 future 版本可能会改变这种行为。

[编辑,回答评论] 为了避免笨拙的区分大小写(如您原始问题中所暗示的),您可以包装 compare进入一个返回三值类型的函数,如下所示:

type comparison = Less | Equal | More

let my_compare a b = match compare a b with
| 0 -> Equal
| c when c>0 -> More
| _ -> Less

关于compare - 比较可以返回 -1、0 和 1 以外的任何值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41137603/

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