Howto use Fmt module to print Lists and Arrays

I’m trying to print ocaml datastructures and use the Fmt module. From the test example (https://github.com/dbuenzli/fmt/blob/master/test/test.ml) I can
some examples on howto use i.e. for numbers but becaue I’m unfamiliar with ocaml I have a hard time to understand howto i.e. printing a list whould be done.

 let str u = Format.asprintf "%a" Fmt.Dump.uchar u in
 str Uchar.min

so I thought I can try:

 let str u = Format.asprintf "%a" Fmt.Dump.list u in
 str []

but I get:

Error: This expression has type 'a Fmt.t -> 'a list Fmt.t
       but an expression was expected of type Format.formatter -> 'b -> unit
       Type 'a Fmt.t = Format.formatter -> 'a -> unit
       is not compatible with type Format.formatter 

I dont really understand how th Format module and pp_xxx works so: Are there examples for the different datatypes for the Fmt module…

If you have a look at the signature of Fmt.list you will see that it requires another formatter to print the element of the list.

So to create a printers for say a list of integers you need Fmt.list and a formatter for the integers, for example Fmt.int. This leads to :

let pp_int_list = Fmt.list Fmt.int
let str l = Format.asprintf "%a" pp_int_list l

Thanks, that worked.

Here’s more loveliness, courtesy of dbuenzli:

Fmt.(pf stdout "%a" (list int) [1;2;3]);;

These combinators are the bee’s knees.

FYI that stdout is Fmt.stdout.

1 Like