I'm a new OCaml-learner, and I'm trying to print some S-expressions, using Jane Street's Sexplib (included with Core):
let rec print_source ?(channel = stdout) sexps =
let formatter = Format.formatter_of_out_channel channel in
Sexp.pp_hum formatter |> List.iter sexps
However, this doesn't seem to be outputting anything to stdout
. If I replace it with a non-Format-using version, it works fine:
let rec print_source ?(channel = stdout) sexps =
Sexp.output_hum channel |> List.iter sexps
Any OCaml know-how is appreciated! (Also, happy to hear if this is super-unidiomatic, and I'm just Doing It Wrong 🤣)
You need to flush the formatter, e.g.,
let rec print_source ?(channel = stdout) sexps =
let formatter = Format.formatter_of_out_channel channel in
Sexp.pp_hum formatter |> List.iter sexps;
Format.pp_print_flush formatter ()
Alternatively, you can use the %!
format specificator to flush directly in your format specification.
With the Format library, we have an extra layer of buffering. Consequent prints to a formatter are accumulated in it and are flushed under certain conditions. Before flushing happens, data is formatted according to the specification, then it is printed into the channel (that may flush data based on its own criteria), after everything is written data is finally flushed, to make sure that everything is outputted into the device, associated with the channel.