CPS
CPS

Reputation: 677

Getting internal value of a type OCaml

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?

Upvotes: 3

Views: 1274

Answers (2)

pad
pad

Reputation: 41290

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

Upvotes: 7

sepp2k
sepp2k

Reputation: 370425

You can access the value using pattern matching:

match value_of_my_type with
| Int i -> do_something_with i

Upvotes: 5

Related Questions