OCaml 选项获取 [英] OCaml Option get

查看:50
本文介绍了OCaml 选项获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 OCaml 的新手,我试图了解您应该如何从 'a 选项中获取值.根据 http://ocaml-lib.sourceforge.net/doc/Option.html 上的文档,有一个类型为 'a option -> 'a 的 get 函数可以满足我的要求.但是当我输入:

I'm new to OCaml, I'm trying to understand how you're supposed to get the value from an 'a option. According to the doc at http://ocaml-lib.sourceforge.net/doc/Option.html, there is a get function of type 'a option -> 'a that does what I want. but when I type:

# 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 的问题)) 而是尝试一下,看看你是否喜欢它.

The traditional way to obtain the value inside any kind of constructor in OCaml is with pattern-matching. Pattern-matching is the part of OCaml that may be most different from what you have already seen in other languages, so I would recommend that you do not just write programs the way you are used to (for instance circumventing the problem with ocaml-lib) but instead try it and see if you like it.

let contents = 
   match z with
   Some c -> c;;

变量 contents 被分配了 3,但是你得到一个警告:

Variable contents is assigned 3, but you get a warning:

警告 8:此模式匹配并非详尽无遗.这是一个例子不匹配的值:无

Warning 8: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: None

在一般情况下,您不会知道要查看内部的表达式必然是 Some c.选择选项类型的原因通常是有时该值可以是 None.编译器在这里提醒您,您没有处理其中一种可能的情况.

In the general case, you won't know that the expression you want to look inside is necessarily a Some c. The reason an option type was chosen is usually that sometimes that value can be None. Here the compiler is reminding you that you are not handling one of the possible cases.

您可以深入"进行模式匹配,编译器仍将检查穷举性.考虑这个带有 (int option) option 的函数:

You can pattern-match "in depth" and the compiler will still check for exhaustivity. Consider this function that takes an (int option) option:

let f x =
  match x with
  Some (Some c) -> c
  | None -> 0
  ;;

这里你忘记了Some (None),编译器告诉你:

Here you forgot the case Some (None) and the compiler tells you so:

警告 8:此模式匹配并非详尽无遗.这是一个例子不匹配的值:Some None

Warning 8: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: Some None

这篇关于OCaml 选项获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆