获取OCaml类型的内部值

CPS*_*CPS 3 ocaml types

我最近刚开始编写OCaml代码,因此这可能是一个天真的问题.但我自己无法解决这个问题.

我在OCaml中有以下类型声明.

type myType =
| Int of int 
Run Code Online (Sandbox Code Playgroud)

现在我有一个myType类型的对象.

有没有办法访问此对象包含的int值?如果有,怎么样?

pad*_*pad 7

你想要的是int从联合类型的值中获取一个值.在OCaml中,我们经常使用模式匹配来分解和转换值:

let get_int v = 
    match v with 
    | Int i -> i
Run Code Online (Sandbox Code Playgroud)

当您在OCaml顶层中尝试该功能时,您会得到类似的内容:

# let v = Int 3;;
val v : myType = Int 3
# get_int v;;
- : int = 3
Run Code Online (Sandbox Code Playgroud)

如果您的工会类型有更多案例,您只需向get_int函数添加更多模式并以适当的方式处理它们.

对于像您的示例那样的单案例联合,您可以直接对其值进行模式匹配:

# let (Int i) = v in i;;
- : int = 3
Run Code Online (Sandbox Code Playgroud)


sep*_*p2k 5

您可以使用模式匹配来访问该值:

match value_of_my_type with
| Int i -> do_something_with i
Run Code Online (Sandbox Code Playgroud)