I am currently trying to do mahjong processing in OCaml, and from the very beginning I come across something that hurts me.
I will give examples based on cards, because I do not want to confuse anyone with the terminology of mahjong.
As in this part of the OCaml User-Defined Types for the skeptic , I want to use type options to describe costumes, cards, and that’s it.
type suit = Club | Diamond | Heart | Spade type value = Jack | Queen | King | Ace | Num of int type card = Card of suit * value | Joker type hand = card list
And it would be very nice if I could write a smart compare function that understands the ordered variants of options.
Ideally, I would write something like this:
type suit = Club < Diamond < Heart < Spade type value = Num of int < Jack < Queen < King < Ace type card = Card of suit * value < Joker type hand = card list
So when i do
List.sort Pervasives.compare [Card(Diamond, Num 3); Joker; Card(Spade, Ace); Card(Diamond, Num 2)]
it gives me
[Card(Diamond, Num 2); Card(Diamond, Num 3); Card(Spade, Ace); Joker]
Alas, ocaml toplevel returns
[Joker; Card(Spade, Ace); Card(Diamond, Num 2); Card(Diamond, Num 3)]
(this is already good!)
Basically, I want a compare function that will display tooltips from a type declaration structure.
I read this article about polymorphic comparison and this similar question, but I'm not sure I want to depend on compare_val .
Do I need to write my own comparison function? If you recommend me write one, do you have tips on how this should be written, especially to reduce the number of cases?
PS: I just heard about deriving(Ord) in Haskell ... Maybe I should stop jumping ...