Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of all variants of a variant type

Tags:

ocaml

In OCaml, is there a way to get a list of all variants of a variant type? For example, in the code below, I had to manually create a list of all variants, which is tedious. It is also error-prone, because I might accidentally omit one of the variants, or include some of them more than once. Is there a way to automate the process of creating a list of all variants?

type letter =
  | A | B | C | D | E | F
  | G | H | I | J | K | L
  | M | N | O | P | Q | R
  | S | T | U | V | W | X
  | Y | Z

(* Manually written list of all variants *)
let letters = [
  A; B; C; D; E; F;
  G; H; I; J; K; L;
  M; N; O; P; Q; R;
  S; T; U; V; W; X;
  Y; Z;
]
like image 715
Flux Avatar asked Oct 18 '25 12:10

Flux


1 Answers

ppx_enumerate is able to generate a list of all values of a finite type. To use a more complete example from its README:

type t =
  | Foo
  | Bar of bool
  | Baz of [`A | `B of unit option]
  [@@deriving enumerate]

will produce a value val all : t list, whose value is equal to

[ Foo; Bar true; Bar false; Baz `A; Baz (`B None); Baz (`B Some ()) ]
like image 146
glennsl Avatar answered Oct 20 '25 21:10

glennsl