OCaml match on string option ref

Viewed 412

How do I do a pattern match on a variable that has type string option ref in OCaml. I need to extract the string part of this variable, but I can't get it to work.

1 Answers

A ref is just a record type with a mutable field called contents:

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

So you pattern match on it just like any other record:

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

Although I would much prefer to unwrap the ref first instead of matching on it:

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