OCaml 匹配字符串选项 ref

OCaml match on string option ref

如何在 OCaml 中对类型为 string option ref 的变量进行模式匹配。我需要提取此变量的字符串部分,但无法正常工作。

A ref 只是一个记录类型,带有一个名为 contents:

的可变字段
type 'a ref = { mutable contents: 'a }

因此,您可以像其他任何记录一样对其进行模式匹配:

match foo with
| { contents = Some str } -> str
| { contents = None } -> ...

尽管我更愿意先打开 ref 而不是匹配它:

match !foo with
| Some str -> str
| None -> ...