Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml: get value's type name

Tags:

ocaml

Is is possible to print value's name in OCaml, for example if I have

type my_type =
  | MyType_First of int
  | MyType_Second of string

and then do something like:

let my_value = MyType_First 0 in
print_string ("my_value is of type " ^ String.from_type my_value ^ ".\n";

can I get "my_value is of type MyType_First." ?

Thank you.

like image 309
Slaus Avatar asked Feb 12 '26 09:02

Slaus


1 Answers

Monomorphic solution:

let from_type = function
  | MyType_First _ -> "MyType_First"
  | MyType_Second _ -> "MyType_Second"

Polymorphic solution: none. (AFAIK, lexical tokens corresponding to constructors are not recorded in the bytecode/binary, even when debugging flags are specified. The only thing one could do is to print the integer ‘identifier’ for the constructor, using some dark Obj.magic.)

like image 83
Stéphane Gimenez Avatar answered Feb 17 '26 21:02

Stéphane Gimenez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!