I have just begun to write OCaml code lately hence this might be a naive question.But i could not figure this out myself.
I have the following type declaration in OCaml.
type myType =
| Int of int
Now i have an object of type myType.
Is there a way to access the value of int that this object holds? If yes, how?
What you want is to get an
intvalue from a value of union types. In OCaml, we often use pattern matching to decompose and transform values:When you try the function in OCaml top-level, you get something like:
If your unions types have more cases, you simply add more patterns to
get_intfunctions and process them in an appropriate way.For single-case unions like your example, you could do pattern matching directly on their values: