Search code examples
ocamlstring-conversion

Converting a constructor name to string in OCaml


I have the following type definitions in my code:

type tag =
| Head
| Title
| Body
| H1
| P;;

type domtree =
| Empty
| Node of tag * string * domtree list;;

I need to print the tags along with the strings. But I couldn't find any way to convert the tag (the constructor names in the first type definition) into strings and concatenate them with the string part of the domtree. Is there any specific way to do this? Does OCaml provide a way to convert non-inbuilt types into strings? I found a similar question in here but I didn't quite understand it.


Solution

  • There is no such a facility built in OCaml and you will need to write yourself the conversion function tag_to_string : tag -> string.

    It is easy to generate the body of this string automatically, for instance, use this sed one-liner:

    sed -e 's/\| \(.*\)/| \1 -> "\1"/'
    

    and paste your tag definition in its standard input. It yields

    | Head -> "Head"
    | Title -> "Title"
    | Body -> "Body"
    | H1 -> "H1"
    | P;; -> "P;;"
    

    and you just have to clean the ;;.

    There is a lot of other solutions to define this boilerplate code, I also love to use Emacs macros for this.