質問

I have a piece of code as follows:

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 does not compile, becase it doesn't consider "(%a, %a)" and "%a%a" as a format anymore. I still would like to use a ternary function, instead of if...then...else... to make the code more succinct. Does anyone know how to amend the code?

役に立ちましたか?

解決

I think the following should work:

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

I've tested the basic idea and it worked for me. I can't test with your code because of the many parts that are missing.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top