Cryptosense is happy to announce the initial release of
ppx_enum is a ppx to derive enum-like modules from variant definitions. It’s inspired by the enum declaration syntax in Python, and various other languages.
Enums are bare variants that are intended to represent a flag that can have more values than just true and false. The idea is that
ppx_enum makes it easier to work with enums, in particular handling the conversion to and from strings. This is useful when (de)serializing values (for example, when serializing to store in a database), and cuts down on repetitive boilerplate code.
Consider the following simple example:
type my_enum = | Foo | Bar | Baz [@@deriving enum]
The use of
[@@deriving enum] will generate the following functions:
let my_enum_to_string = function | Foo -> "Foo" | Bar -> "Bar" | Baz -> "Baz" let my_enum_from_string = function | "Foo" -> Ok Foo | "Bar" -> Ok Bar | "Foo" -> Ok Foo | _ -> Error ... let my_enum_from_string_exn = function | "Foo" -> Foo | "Bar" -> Bar | "Foo" -> Foo | _ -> invalid_arg ...
Since we found this was something we were doing a lot in our code, the use of
ppx_enum has improved readability, reduced the need for boilerplate tests and made the conversions less error prone (as it eliminates bugs caused by typos in the string conversion methods).
It’s in a beta release at this point so any feedback is appreciated!