2013-10-25 37 views
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不能編譯,becase的它不考慮"(%a, %a)""%a%a"的格式了。我還是想用一個三元函數,而不是if...then...else...使代碼更簡潔。有誰知道如何修改代碼?

回答

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 

我測試的基本概念,它爲我工作。由於缺少許多部分,我無法使用您的代碼進行測試。