我最近才开始编写 OCaml 代码,因此这可能是一个幼稚的问题。但我自己无法弄清楚。
我在 OCaml 中有以下类型声明。
type myType =
| Int of int
现在我有一个 myType 类型的对象。
有没有办法访问这个对象持有的 int 值?如果是,如何?
您想要的是int
从联合类型的值中获取值。在 OCaml 中,我们经常使用模式匹配来分解和转换值:
let get_int v =
match v with
| Int i -> i
当您在 OCaml 顶层尝试该功能时,您会得到如下信息:
# let v = Int 3;;
val v : myType = Int 3
# get_int v;;
- : int = 3
如果您的联合类型有更多案例,您只需向get_int
函数添加更多模式并以适当的方式处理它们。
对于像您的示例这样的单例联合,您可以直接对其值进行模式匹配:
# let (Int i) = v in i;;
- : int = 3
您可以使用模式匹配访问该值:
match value_of_my_type with
| Int i -> do_something_with i