BitTickler
BitTickler

Reputation: 11875

OCaml equivalent to f# "%A"

in F#, the following is a no brainer:

let l = [1;2;3;4]
let s = sprintf "%A" l

where "%A" prints a formatted version of virtually any common, even recursive data structure.

Is there something similarly easy in ocaml?

Upvotes: 2

Views: 118

Answers (1)

ivg
ivg

Reputation: 35210

There is something close, the %a specificator accepts two arguments, the first is a pretty printer for type 'a, and the second is a value of type 'a. The type of the printer, depends on the kind of used printf function. For example,

open Core_kernel.Std
open Format

printf "%a" Int63.pp Int63.one

Of course, this depends heavily on a good support from a library. If there is no pp function, provided for the type, then it is pretty useless.

Also there is a custom_printf syntax extension available for both - pp and ppx. In this extension you place a module name in the place of specificator. The module must have a to_string function. The ppx version, requires an exclamation mark before the format string:

printf !"%{Int63}" Int63.one

There is also a dump function, available over the Internet. In particular you can find it in the Batteries library. It recurse over the data representation and print it in a more or less human readable representation. But this is not relate to the formatted output.

Upvotes: 2

Related Questions