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;
]
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 ()) ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With