OCaml 选项获取

标签 ocaml option

我是 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/

相关文章:

cmake - CMake子项目中的覆盖选项

php - 在单个产品页面上添加一个复选框,这会在 Woocommerce 中增加额外费用

visual-studio - 如何告诉 Visual Studio 2010 记住“查找”对话框的位置?

java - 将组合框中的选定值放入<a href>以发送到servlet

ocaml - 在 OCaml 中处理循环依赖

syntax-error - 仿函数中的 OCaml 语法错误

ocaml - 为什么 let f = List.map fst 与 let g x = List.map fst x 之间的推断类型不同

algorithm - 使用 OCaml 中的列表找到下一个最大的数字

javascript - 如何使用JQuery/JS动态获取表单选项文本

module - OCaml 中的类型共享 - 类型检查器错误