How do the OCaml operators < and > work with non-integer types?

痞子三分冷 提交于 2019-12-12 22:06:32

问题


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

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?

Thanks!


回答1:


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.

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.

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 ))


来源:https://stackoverflow.com/questions/31152244/how-do-the-ocaml-operators-and-work-with-non-integer-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!