首页 > 解决方案 > 字符串选项 ref 上的 OCaml 匹配

问题描述

如何对具有string option refOCaml 类型的变量进行模式匹配。我需要提取这个变量的字符串部分,但我无法让它工作。

标签: pattern-matchingocaml

解决方案


Aref只是一个带有可变字段的记录类型,称为contents

type 'a ref = { mutable contents: 'a }

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

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

虽然我更喜欢打开第ref一个而不是匹配它:

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

推荐阅读