字符串和格式的转换

时间:2013-10-25 21:36:56

标签: ocaml pretty-print printf

我有一段代码如下:

let pp_e (chan: out_channel) (e: e) =
  ...

(* ternary operator *)
let tern (b: bool) v0 v1 =
  if b then v0 else v1

let pp_x (chan: out_channel) (b: bool) (x: x) =
  let e0, e1 = ... in
  Printf.fprintf chan (tern b "(%a, %a)" "%a%a") pp_e e0 pp_e e1

Error: This expression has type string but an expression was expected of type
     ('a -> 'b -> 'c -> 'd -> 'e, out_channel, unit) format =
       ('a -> 'b -> 'c -> 'd -> 'e, out_channel, unit, unit, unit, unit)
       format6

pp_x无法编译,因为它不再将"(%a, %a)""%a%a"视为格式。我仍然想使用三元函数而不是if...then...else...来使代码更简洁。有谁知道如何修改代码?

1 个答案:

答案 0 :(得分:0)

我认为以下内容应该有效:

let pp_x (chan: out_channel) (b: bool) (x: x) =
    let fmt0 = format_of_string "(%a, %a)" in
    let fmt1 = format_of_string "%a%a" in
    let e0, e1 = ... in
    Printf.fprintf chan (tern b fmt0 fmt1) pp_e e0 ppe e1

我已经测试了基本想法,它对我有用。由于缺少许多部分,我无法使用您的代码进行测试。