OCaml: get value's type name

让人想犯罪 __ 提交于 2019-12-04 04:37:07

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/7380755/ocaml-get-values-type-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!