通常如何将变体类型的值转换为字符串?

How do you generically convert values of variant types to strings?

假设我有一个由以下数据构造函数组成的求和类型...

type Entity =
 | Student 
 | Staff
 | Classes

有没有一种方法可以将给定总和类型的值多态转换为字符串类型的值,而无需求助于以下内容。

let showEntity = e =>
 switch (e){
 | Student   => "Student" 
 | Staff     => "Staff"
 | Classes   => "Classes"

使用OCaml/Reason中的ppx预处理完成,例如使用ppx_deriving库1,

[@deriving show({with_path: false})]
type t = Hello | World;

let main () =
  print_endline("Hello, " ++ show(World));

main ();

和运行它与dune exec ./main.exe一起向我们展示了我们心爱的

dune exec ./main.exe
Hello, World

前提是代码在main.re文件中,并且同文件夹下有一个名为dune的文件,内容如下

(executable
 (name main)
 (preprocess (pps ppx_deriving.std)))

并且 ppx_deriving 库和 dune 已安装,假设您使用的是 opam。如果您使用的是 bucklescript,请安装 bs-deriving 包。事实上,有很多库提供派生器,以及不同的派生器,所以很难推荐一个(并且建议库不在 SO 的范围内,因此将其视为一般演示)。


1) 另请注意,如果我们使用不带参数的派生器,则 show 派生器采用参数 {with_path: false),例如

 [@deriving show]
 type t = Hello | World;

它将显示以模块名称为前缀的名称,这可能不是您想要的。