Search code examples
ocamlpretty-print

How to return a pretty printed string using Format.fprintf function?


I am trying to understand and use Format.fprintf for a piece of code in a module. I have a function like this

let some_function fmt s = match s with
  | For(exp,_) -> Format.fprintf fmt "something here"
  | Assume x-> Format.fprintf fmt "something here as well"

I want to modify this function to return a string. Printf.sprintf is not an option because of some pretty printers I use in the original code. Please help.


Solution

  • Use Format.asprintf:

    let string_of_s = Format.asprintf "%a" some_function s
    

    I do not recommend to use Format.sprintf since it has a limited type. For example the following does not type-check:

    let string_of_s_ill_typed = Format.sprintf "%a" some_function s