开发者

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 op开发者_C百科tion in printf, but how do I access the string within the lock within the rdwrlock?


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜