Version française
Home     About     Download     Resources     Contact us    
Browse thread
printf "%a" vs sprintf "%a"
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Bertrand Jeannet <Bertrand.Jeannet@i...>
Subject: printf "%a" vs sprintf "%a"

For people that do not use OCaml batteries, a sprintf function similar 
to  (Printf|Format).printf can be defined using kfprintf:

let sprintf format =
   let buffer = Buffer.create 512 in
   let fmt = Format.formatter_of_buffer buffer in
   Format.kfprintf
     (begin fun fmt ->
       Format.pp_print_flush fmt ();
       let s = Buffer.contents buffer in
       Buffer.clear buffer;
       s
     end)
     fmt
     format

The types are different:
Format.fprintf : Format.formatter -> ('a, Format.formatter, unit, unit) 
format4 -> 'a
val sprintf : ('a, Format.formatter, unit, string) format4 -> 'a = <fun>

but that is normal, as sprintf should return a string.

Bertrand Jeannet