3

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?

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
CPS
  • 677
  • 2
  • 6
  • 9
  • 2
    Btw, `object` is not correct term in this context. I think you should say `value of myType`. OCaml allows OOP and object is a term another entities. But objects are values too. – Kakadu Oct 22 '12 at 14:47
  • 2
    If your teaching material does not include an answer to this question in a prominent place, you need to get better material. Have a look at this StackOverflow question, [Which English tutorial would you advise to learn OCaml?](http://stackoverflow.com/q/9358553/298143), for pointers. – gasche Oct 22 '12 at 15:22

2 Answers2

7

What you want is to get an int value from a value of union types. In OCaml, we often use pattern matching to decompose and transform values:

let get_int v = 
    match v with 
    | Int i -> i

When you try the function in OCaml top-level, you get something like:

# let v = Int 3;;
val v : myType = Int 3
# get_int v;;
- : int = 3

If your unions types have more cases, you simply add more patterns to get_int functions and process them in an appropriate way.

For single-case unions like your example, you could do pattern matching directly on their values:

# let (Int i) = v in i;;
- : int = 3
pad
  • 41,040
  • 7
  • 92
  • 166
5

You can access the value using pattern matching:

match value_of_my_type with
| Int i -> do_something_with i
sepp2k
  • 363,768
  • 54
  • 674
  • 675