gpt4 book ai didi

OCaml:获取值的类型名称

转载 作者:行者123 更新时间:2023-12-03 07:49:49 26 4
gpt4 key购买 nike

是否可以在 OCaml 中打印值的名称,例如,如果我有

type my_type =
| MyType_First of int
| MyType_Second of string

然后执行以下操作:
let my_value = MyType_First 0 in
print_string ("my_value is of type " ^ String.from_type my_value ^ ".\n";

我能得到“my_value 的类型为 MyType_First”吗? ?

谢谢你。

最佳答案

单态解决方案:

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

多态解决方案:无。 (AFAIK,即使指定了调试标志,对应于构造函数的词法标记也不会记录在字节码/二进制文件中。唯一能做的就是打印构造函数的整数“标识符”,使用一些深色 Obj.magic 。)

关于OCaml:获取值的类型名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7380755/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com