OCaml匹配字符串选项ref

问题描述

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

解决方法

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 -> ...