OCaml运算符如何<和>使用非整数类型? [英] How do the OCaml operators < and > work with non-integer types?

查看:75
本文介绍了OCaml运算符如何<和>使用非整数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇大于(>)和小于(<)运算符如何与OCaml中不是int,float或double的类型一起使用.

I'm curious how the greater than (>) and less than (<) operators work with types that are not int, float, or double in OCaml.

例如,我能够发现字符串"a">"b",但是有一些引用列出了所有非数值数据类型的约定.此外,这些运算符如何跨类型工作?例如是"a"> true还是"a"<是真的吗?

For instance, I was able to discover that string "a" > "b" but is there some reference that lists the conventions for all non-numerical data types. Furthermore, how do these operators work across types? e.g. Is "a" > true or is "a" < true?

最后,它们将如何在用户定义的数据类型上工作?

Finally, how would these work across a user-defined data type?

谢谢!

推荐答案

OCaml <><=>=运算符仅适用于两个相同类型的值,因此表达式无效.但是,它们适用于所有类型(注意事项如下).您可以在 Pervasives 模块.

The OCaml <, >, <=, >= operators only work with two values of the same type, so the expression "a" > true is invalid. However, they work for all types (with caveats below). You can find the definitions of these operators in the Pervasives module.

这些运算符的顺序仅针对简单值(整数,字符,字符串,字节序列和浮点数)定义.在这些情况下,文档说它们给出通常的顺序".

The order for these operators is defined only for simple values (integers, characters, strings, byte sequences, and floating). In these cases the documentation says they give "the usual ordering".

字符串和字节序列的通常顺序是字典顺序.对于字符串,大小写很重要.

The usual ordering for strings and byte sequences is lexicographic order. For strings, case is significant.

对于复合值,只能保证其顺序与=一致,并且要保持一致的顺序.

For compound values the order is only guaranteed to be consistent with = and to be a consistent ordering.

据我所知,没有为type abc = A | B | C之类的简单用户定义类型定义顺序.我没想到会是这种情况,但这就是我在文档中看到的.实际上,诸如ABC之类的常量构造函数的值将按照声明的顺序进行排序,第一个值最小.

As far as I can see, order is not defined for simple user-defined types like type abc = A | B | C. I didn't expect this to be the case, but that's what I see in the documentation. In practice, the values of constant constructors like A, B, C, will be ordered in the order of declaration with the first value the smallest.

我也看不到falsetrue之间的顺序的定义.再次,这是令人惊讶的.实际上,false小于true.

I also don't see a definition of the order between false and true. Again, this is surprising. In practice, false is less than true.

值得注意的是,不能保证循环值之间的比较会终止.此外,包含函数的值之间的比较可能会引发异常.这些可能会导致意外的问题,有时甚至是严重的问题.

It is worth noting that comparisons between cyclic values is not guaranteed to terminate. Also, comparison between values that contain functions may raise an exception. These can cause unexpected problems, sometimes serious ones.

$ ocaml
        OCaml version 4.02.1

# (+) < (+);;
Exception: Invalid_argument "equal: functional value".
# let rec cycle = 1 :: cycle;;
val cycle : int list = [1; <cycle>]
# cycle < cycle;;
(( Does not terminate ))

这篇关于OCaml运算符如何&lt;和&gt;使用非整数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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