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
.