Consider the following code, where all the arms of the enum as “parameter less”
type my_enum = A | B | C | D | E
let _foo (x : my_enum) : int =
match x with
| A -> 0
| B -> 1
| C -> 2
| D -> 3
| E -> 4
let _bar (n : int) : my_enum =
match n with
| 0 -> A
| 1 -> B
| 2 -> C
| 3 -> D
| 4 -> E
| _ -> failwith "not handled"
This is a bit tedious / error prone to maintain. Is there some ppx that will auto derive _foo / _bar for me ?
For foo at least, Obj.magic
should do the trick. Otherwise, it should not be too hard to write that ppx yourself
ppx_deriving has an enum deriver ? Here’s a bit from the test
type t = Aa | Ba | Ca [@@deriving enum, show]
let test_auto ctxt =
assert_equal ~printer:string_of_int 0 (to_enum Aa);
assert_equal ~printer:string_of_int 1 (to_enum Ba);
assert_equal ~printer:string_of_int 2 (to_enum Ca);
assert_equal ~printer:show Aa (get (of_enum 0));
assert_equal ~printer:show Ba (get (of_enum 1));
assert_equal ~printer:show Ca (get (of_enum 2));
assert_equal ~printer:string_of_int 0 min;
assert_equal ~printer:string_of_int 2 max
1 Like