nphx
nphx

Reputation: 1427

Function modifying StringFormat

I want to create a function that would take a StringFormat as a parameter, prepend an arbitrary string to it and return a function that takes the correct number and type of parameters and returns a string created with sprintf and the altered format.

The goal is to create a function producing results like this (the string to prepend being #):

xprintf "%d-%.2f" 5 5. // -> "#5-5.00"
xprintf "%A" [42] // -> "#[42]"

I've naively tried to do the following:

let xprintf (format: Printf.StringFormat<'a>) = Printf.StringFormat<'a>(string format |> (+) "#") |> sprintf

That does compile, but I'm getting an InvalidCastException when I use it during runtime. I'm starting to think that there is no way this approach could work. Could a custom PrintFormat be the way to go? Articles/guides on how to work with the various formatters on a non-trivial level seem to be extremely scarce.

Upvotes: 2

Views: 132

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243041

You can do this using Printf.kprintf. It returns the formatted string via a continuation, which lets you do whatever you need with the formatted string:

let xprintf fmt =
  Printf.kprintf (fun s -> "#" + s) fmt

EDIT: I think there is a way to work with the format strings directly, but I have never done that. If you wanted to add an additional parameter, you can still do that using kprintf, just by doing one more formatting in the continuation:

let xprintf fmt num =
  Printf.kprintf (sprintf "# %d %s" num) fmt

Upvotes: 4

Related Questions