Robz
Robz

Reputation: 1767

Combine multiple variants into one variant

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?

Upvotes: 4

Views: 765

Answers (2)

loxs
loxs

Reputation: 1546

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 ];

Upvotes: 6

Étienne Millon
Étienne Millon

Reputation: 3028

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.

Upvotes: 5

Related Questions