OCaml: get value's type name

前端 未结 2 700
刺人心
刺人心 2021-01-21 03:22

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 th

相关标签:
2条回答
  • 2021-01-21 03:28

    What you want is a simpler form of generic print and is not available in OCaml as such, but some workarounds exist - e.g. deriving.

    0 讨论(0)
  • 2021-01-21 03:43

    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.)

    0 讨论(0)
提交回复
热议问题