Is there a way to combine multiple variants together into one? Something like this:
type pet = Cat | Dog;
type wild_animal = Deer | Lion;
type animal = pet | wild_animal;
This is a syntax error, but I would like animal to become a variant with four constructors: Cat | Dog | Deer | Lion
. Is there a way to do this?
Polymorphic variants are created with exactly your idea in mind. They are less efficient as memory representation, but it shouldn't matter if you are going to compile it to JavaScript:
type pet = [ | `Cat | `Dog];
type wild_animal = [ | `Deer | `Lion];
type animal = [ pet | wild_animal ];
I would like animal to become a variant with four constructors: Cat | Dog | Deer | Lion. Is there a way to do this?
You can not do that directly. That would mean that Cat
has type pet
, but also type wild_animal
. This is not possible using normal variants, which always have a single type. This is however possible with polymorphic variants, as the other answer describes.
Another solution, more common (but it depends on what you are trying to achieve), is to define a second layer of variants:
type pet = Cat | Dog
type wild_animal = Deer | Lion
type animal = Pet of pet | Wild_animal of wild_animal
That way, Cat
has type pet
, but Pet Cat
has type animal
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With