Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 313
Robz Avatar asked Dec 18 '22 22:12

Robz


2 Answers

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 ];
like image 154
loxs Avatar answered Jan 13 '23 19:01

loxs


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.

like image 45
Étienne Millon Avatar answered Jan 13 '23 18:01

Étienne Millon