Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom formatters in Format.fprintf and Format.sprintf #6176

Closed
vicuna opened this issue Sep 13, 2013 · 3 comments
Closed

Custom formatters in Format.fprintf and Format.sprintf #6176

vicuna opened this issue Sep 13, 2013 · 3 comments

Comments

@vicuna
Copy link

vicuna commented Sep 13, 2013

Original bug ID: 6176
Reporter: @dbuenzli
Assigned to: @gasche
Status: closed (set by @xavierleroy on 2015-12-11T18:25:47Z)
Resolution: fixed
Priority: normal
Severity: feature
Category: standard library
Monitored by: @gasche @jmeber @dbuenzli

Bug description

One of the annoyance of the Format module is that if you define a pretty printer pp_v for your value you can use it with Format.fprintf "%a" pp_v v but not directly with Format.sprintf "%a" pp_v v.

Usually I work around by having a to_string function generated from my pp_v as follows:

let to_string_of_formatter pp v = (* NOT thread safe. *)
Format.fprintf Format.str_formatter "%a" pp v;
Format.flush_str_formatter ()

And then do a Format.sprintf "%s" (to_string v).

However it would be simpler to have a function Format.spp, defined as follows:

let spp pp_v () v = (* NOT thread safe. *)
Format.fprintf Format.str_formatter "%a" pp_v v;
Format.flush_str_formatter ()

That would allow to write Format.sprintf "%a" (Format.spp pp_v) v

P.S. Maybe Format.spp should not use Format.str_formatter, I was surprised it worked, thought the flush would trip the Format.sprintf.

@vicuna
Copy link
Author

vicuna commented Sep 13, 2013

Comment author: @lpw25

I've also been annoyed by this in the past.

Perhaps, spp should be defined as something like:

let spp pp_v () v =
  let b = Buffer.create 16 in 
  let ppf = formatter_of_buffer b in
  pp_v ppf v;
  pp_flush_queue ppf false;
  Buffer.contents b

@vicuna
Copy link
Author

vicuna commented Mar 12, 2014

Comment author: @dbuenzli

Thanks to commit faf9cb4 by Pierre Weiss which wasn't mentioned in the release notes, I happily discovered that this issue is now fixed in 4.01.0 by using Format.asprintf.

@vicuna
Copy link
Author

vicuna commented Mar 13, 2014

Comment author: @gasche

Thanks to commit faf9cb4 by Pierre Weiss which wasn't mentioned in the release notes, I happily discovered that this issue is now fixed in 4.01.0 by using Format.asprintf.

Good catch! Indeed I missed this change when preparing the release notes, as I started from the CHANGES which Pierre forgot to update alongside this commit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants