Dear Kakadu, Gabriel, Edouard,
thanks a lot for the valuable hints! It is not so obvious from the manual. For those curious (like me) how the types of such functions might look like, here
are a few examples:
(* 'a is a function from the arguments of the first format (prefix) to 'c.
'c is a function from the arguments of the second format (fmt) to 'd.
'd is a function from the arguments of the third format (postfix) to unit.
So 'a is a function from arguments required by all formats to unit.
And 'c is a function from arguments required by the last 2 formats and to unit. *)
let bracketprintf
(prefix : ('a, out_channel, unit, unit, 'b, 'c) format6)
(suffix : ('d, out_channel, unit, 'e, unit, unit) format6)
(oc : out_channel)
(fmt : ('c, out_channel, unit, 'b, 'e, 'd) format6)
: 'a
= Printf.fprintf oc (prefix ^^ fmt ^^ suffix);;
(* 'a is a function from the arguments of <fmt> followed by two int arguments for the supplied suffix to unit.
The two string arguments for the internal prefix are supplied by the string -> string -> 'a *)
let myprintf1 (oc : out_channel) (fmt : ('a, out_channel, unit, unit, unit, int -> int-> unit) format6) : string -> string -> 'a =
bracketprintf "Prefix1 %s %s\n" "Suffix1 %d %d\n" oc fmt
;;
(* As above, but with the ^^ directly in the function *)
let myprintf2 (oc : out_channel) (fmt : ('a, out_channel, unit, unit, unit, int -> int-> unit) format6) : string -> string -> 'a =
Printf.fprintf oc ("Prefix2 %s %s\n" ^^ fmt ^^ "Suffix2 %d %d\n")
;;
(* As above, but the two string parameters for the prefix are supplied internally *)
let myprintf3 (oc : out_channel) (fmt : ('a, out_channel, unit, unit, unit, int -> int-> unit) format6) : 'a =
Printf.fprintf oc ("Prefix3 %s %s\n" ^^ fmt ^^ "Suffix3 %d %d\n") "abc" "def"
;;
(* If parameters for the suffix shall be applied internally, kfprintf needs to be used instead of format concatenation *)
let myprintf4 (oc : out_channel) (fmt : ('a, out_channel, unit, unit, unit, unit) format6) : 'a =
Printf.kfprintf (fun oc -> Printf.fprintf oc "Suffix4 %d %d\n" 5 6) oc ("Prefix4 %s %s\n" ^^ fmt) "abc" "def"
;;
let () =
let test = open_out "Test.txt" in
myprintf1 test "%d %d\n" "abc" "def" 3 4 5 6;
myprintf2 test "%d %d\n" "abc" "def" 3 4 5 6;
myprintf3 test "%d %d\n" 3 4 5 6;
myprintf4 test "%d %d\n" 3 4;
Best regards,
Michael
Intel Deutschland GmbH
Registered Address: Am Campeon 10-12, 85579 Neubiberg, Germany
Tel: +49 89 99 8853-0, www.intel.de
Managing Directors: Christin Eisenschmid, Christian Lamprechter
Chairperson of the Supervisory Board: Nicole Lau
Registered Office: Munich
Commercial Register: Amtsgericht Muenchen HRB 186928