我是 OCaml 的新手,我试图了解您应该如何从 'a 选项中获取值(value)。根据文档 http://ocaml-lib.sourceforge.net/doc/Option.html ,有一个类型为 'a option -> 'a 的 get 函数可以满足我的要求。但是当我输入:
# let z = Some 3;;
val z : int option = Some 3
# get z;;
Error: Unbound value get
# Option.get z;;
Error: Unbound module Option
为什么这不起作用?
最佳答案
在 OCaml 中任何类型的构造函数中获取值的传统方法是使用模式匹配。模式匹配是 OCaml 的一部分,它可能与您已经在其他语言中看到的最不同,因此我建议您不要只按照习惯的方式编写程序(例如绕过 ocaml-lib 的问题) ) 而是尝试一下,看看您是否喜欢它。
let contents =
match z with
Some c -> c;;
变量
contents
已分配 3
,但您会收到警告:Warning 8: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: None
在一般情况下,你不会知道你想看里面的表达式一定是
Some c
.选择选项类型的原因通常是有时该值可以是 None
.编译器在这里提醒您,您没有处理其中一种可能的情况。您可以“深入”进行模式匹配,编译器仍将检查穷举性。考虑这个接受
(int option) option
的函数:let f x =
match x with
Some (Some c) -> c
| None -> 0
;;
在这里你忘记了案例
Some (None)
编译器告诉你:Warning 8: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: Some None
关于OCaml 选项获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12288628/