therewillbecode
therewillbecode

Reputation: 7180

How do you generically convert values of variant types to strings?

Say I have a sum type consisting of the following data constructors...

type Entity =
 | Student 
 | Staff
 | Classes

Is there a way of polymorphically converting values from a given sum type into values of type string which does not resort to the below.

let showEntity = e =>
 switch (e){
 | Student   => "Student" 
 | Staff     => "Staff"
 | Classes   => "Classes"

Upvotes: 0

Views: 231

Answers (1)

ivg
ivg

Reputation: 35270

It is done using ppx preprocessing in OCaml/Reason, for example, using the ppx_deriving library1,

[@deriving show({with_path: false})]
type t = Hello | World;

let main () =
  print_endline("Hello, " ++ show(World));

main ();

and running it with dune exec ./main.exe shows us our beloved

dune exec ./main.exe
Hello, World

provided that the code is in the main.re file, and there is a file named dune in the same folder with the following content

(executable
 (name main)
 (preprocess (pps ppx_deriving.std)))

and that the ppx_deriving library and dune are installed, assuming that you're using opam. If you're using bucklescript, then install the bs-deriving package. In fact, there are plenty of libraries that provide derivers, as well as different derivers, so it is hard to suggest one (and suggesting a library would be out of the scope for SO, so consider this as a general demonstration).


1) Note also, that the show deriver takes a parameter {with_path: false), if we will use the deriver without parameters, e.g.,

 [@deriving show]
 type t = Hello | World;

it will show names prefixed with a module name, which is probably not what you want.

Upvotes: 3

Related Questions