Search code examples
typesocamlvariantreason

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?


Solution

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