Rowhawn
Rowhawn

Reputation: 1479

How can I print the string value of something wrapped in another type in Ocaml?

I'm attempting to use Printf.sprintf to print out a value that is within a type of multiple options

type tid = int

type lock = string

type rdwrlock = 
  | Rdlock of lock
  | Wrlock of lock

type rdwrlockid = rdwrlock * tid

Basically, I want to print out a rdwrlockid, which is (rdwrlock*tid) and I can print out the tid easily using the %d option in printf, but how do I access the string within the lock within the rdwrlock?

Upvotes: 2

Views: 134

Answers (1)

barti_ddu
barti_ddu

Reputation: 10309

Sticking to your example it could be done as follows:

let y, z = (Rdlock "a", 1) in
Printf.printf "%d %s\n" z (match y with Rdlock r -> r | Wrlock w -> w)

It may be simplified a bit:

type lck = READ | WRITE
type lckid = lck * tid

let k, i = (READ, 1) in
Printf.printf "%d %s\n" i (match k with READ -> "R" | WRITE -> "W");

Or if you do need string representation of lock oftenly, you may write a helper function:

let string_of_lock k =
    match k with
    | READ  -> "R"
    | WRITE -> "W"

And then use it in printf:

Printf.printf "%d %s\n" i (string_of_lock k)

Upvotes: 3

Related Questions