Compare matches OCaml

I loved this syntax in OCaml

match myCompare xy with |Greater-> |Less-> |Equal-> 

However, this requires 2 things, a custom type and the function myCompare, which returns my custom type.

Would it be all the same to do this without following the above steps?

The pervasives module seems to have a “comparison” that returns 0 if it is equal, pos int when greater, and neg int less. Can they be matched? Conceptually in a similar way (which does not compile):

 match myCompare xy with | (>0) -> | (0) -> | (<0) -> 

I know that I can just use if statements, but template comparison is more elegant for me. Is there a simple (if not standard) way to do this?

+4
source share
2 answers

Is there an easy way to do this?

Not!

The advantage of match over what switch does in another language is that OCaml match tells you if you thought about covering all cases (and this allows you to compare depth and compile more efficiently, but it can also be considered an advantage of types) . You will lose the advantage of warning if you do something stupid if you start using arbitrary conditions instead of patterns. You just get a design with the same drawbacks as switch .

This, in fact, yes!

You can write:

 match myCompare xy with | z when (z > 0) -> 0 | 0 -> 0 | z when (z < 0) -> 0 

But using when makes you lose the advantage of warning if you do something stupid.

Custom Type type comparison = Greater | Less | Equal type comparison = Greater | Less | Equal type comparison = Greater | Less | Equal and pattern matching across only three constructors is the right way. It documents what myCompare does instead of letting it return an int , which could also represent a file descriptor in another language. Type definitions have no run-time costs. There is no reason not to use it in this example.

+6
source

You can use a library that already provides these functions for comparing returned options. This applies to the BatOrd battery module, for example.

Otherwise, it is best to determine the type and create a conversion function from integers to comparisons.

 type comparison = Lt | Eq | Gt let comp n = if n < 0 then Lt else if n > 0 then Gt else Eq (* ... *) match comp (Pervasives.compare foo bar) with | Lt -> ... | Gt -> ... | Eq -> ... 
+4
source

Source: https://habr.com/ru/post/1498704/


All Articles