# Auto derive enum conversions

**URL:** <https://discuss.ocaml.org/t/auto-derive-enum-conversions/12119>\
**Category:** Learning\
**Created:** [May 7, 2023, 3:37pm UTC](https://discuss.ocaml.org/t/auto-derive-enum-conversions/12119 "2023-05-07T15:37:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![zeroexcuses](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/zeroexcuses/32/1692_2.png) [@zeroexcuses](https://discuss.ocaml.org/u/zeroexcuses)\
**Post date:** [May 7, 2023, 3:37pm UTC](https://discuss.ocaml.org/t/auto-derive-enum-conversions/12119/1 "2023-05-07T15:37:31Z")

</div>

Consider the following code, where all the arms of the enum as “parameter less”

```auto
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 ?

---

<div class="post-metadata">

**Author:** ![EmileTrotignon](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/emiletrotignon/32/5913_2.png) [@EmileTrotignon](https://discuss.ocaml.org/u/EmileTrotignon)\
**Post date:** [May 7, 2023, 5:26pm UTC](https://discuss.ocaml.org/t/auto-derive-enum-conversions/12119/2 "2023-05-07T17:26:30Z")

</div>

For foo at least, `Obj.magic` should do the trick. Otherwise, it should not be too hard to write that ppx yourself

---

<div class="post-metadata">

**Author:** ![Chet\_Murthy](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/chet_murthy/32/1501_2.png) [@Chet\_Murthy](https://discuss.ocaml.org/u/Chet_Murthy)\
**Post date:** [May 7, 2023, 5:42pm UTC](https://discuss.ocaml.org/t/auto-derive-enum-conversions/12119/3 "2023-05-07T17:42:42Z")

</div>

ppx\_deriving has an enum deriver ? Here’s a bit from the test

```auto
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

```
