我正在阅读 Jason 的书,并面对以下代码。
let x = ref None;;
let one_shot y =
match !x with
None ->
x := Some y;
y
| Some z -> z;;
我不明白 Some 和 None 这里的含义。
我正在阅读 Jason 的书,并面对以下代码。
let x = ref None;;
let one_shot y =
match !x with
None ->
x := Some y;
y
| Some z -> z;;
我不明白 Some 和 None 这里的含义。
None类似于is not set或null。如果值匹配None,则不设置该值。
Someis something like is set with something or not null。如果一个值匹配Some z,这个值就有一个值z。
在这里,函数one_shot看起来!x(地址中的变量x)。如果它的None则设置y并返回y,如果是Some z则返回z
它们是内置 OCaml 数据类型的构造函数,您可以这样定义自己:
type 'a option =
| None
| Some of 'a
这意味着Noneif 是'a optionany的类型'a,例如,Some 3是一个int option.
这些是内置选项类型的构造函数,定义如下:
type 'a option = None | Some of 'a
它是一种通常有用的求和类型,用于表示可选值,在您的问题中显示的示例中如此使用。
这里值得注意的是,它是一种内置类型(而不是在Pervasives模块中提供),因为它用于推断具有可选参数的函数类型。
例如,考虑以下情况:
let f ?x () =
match x with
| Some x -> x
| None -> 0
该函数具有以下类型:
val f: ?x:int -> unit -> int