This solution works indeed on my ocaml version and it has the benefit of being very fast. Is anyone aware of a safer solution that is guaranteed not to break in the future?
It seems to me that there is a pretty natural coding pattern underlying my question. For example, a simple and efficient way to represent a function of type enum -> t is to simply store an array of t values of size the length of the enum. The enum_of_int and int_of_enum functions would then be needed to manipulate such a representation.
# #require "ppx_deriving.enum" ;;
# type t = A | B | C | D [@@deriving enum] ;;
type t = A | B | C | D
val min : int = 0
val max : int = 3
val to_enum : t -> int = <fun>
val of_enum : int -> t option = <fun>
The only thing that is possibly missing from this solution in my opinion is an of_enum_exn: int -> t function that does not allocate an option and can be compiled into a quasi no-op by the compiler. But I am nitpicking here.