11

is there a cleaner way of doing this? I'm trying to do pattern matching of a

(a' option * (char * nodeType) list ref

the only way I found was doing this :

match a with
| _, l -> match !l with
  | (c, n)::t -> doSomething 

Wouldn't there be a way to match a with something else like ...

match a with
| _, ref (c,n)::t -> doSomething

... or something similar? In this example it doesn't look heavy to just do another match with, but in the real case it can somewhat be...

Thanks for your answers.

Pacane
  • 20,273
  • 18
  • 60
  • 97

2 Answers2

13

The ref type is defined as a record with a mutable field:

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

This means that you can pattern match against it using record syntax like this:

match a with
| _, { contents = (c,n)::t } -> doSomething
sepp2k
  • 363,768
  • 54
  • 674
  • 675
13

In OCaml a ref is secretly a record with a mutable field named contents.

match a with
| _, { contents = (c, n) :: t } -> (* Do something *)
Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108