1

我有一段代码如下:

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...让代码更简洁。有谁知道如何修改代码?

4

1 回答 1

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

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

于 2013-10-25T21:48:27.717 回答