如何在Ocaml中打印包含在其他类型中的内容的字符串值?

时间:2011-05-05 07:16:48

标签: printing types ocaml printf

我正在尝试使用Printf.sprintf打印出多个选项类型中的值

    type tid = int

    type lock = string

    type rdwrlock = 
      | Rdlock of lock
      | Wrlock of lock

    type rdwrlockid = rdwrlock * tid

基本上,我想打印出一个“rdwrlockid”,它是(rdwrlock * tid),我可以使用printf中的%d选项轻松打印出“tid”,但是我如何访问锁中的字符串在rdwrlock内?

1 个答案:

答案 0 :(得分:3)

坚持你的例子,可以按如下方式完成:

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

可能会简化一下:

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");

或者如果你经常需要lock的字符串表示,你可以写一个辅助函数:

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

然后在printf中使用它:

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