How can I best create a function (lets call it myPrint) that takes sprintf, a format string, and a list of strings as arguments and produces a result such that each element in the list of strings is applied/folded into sprintf?
i.e.
myPrint (sprintf "one: %s two: %s three: %s") ["first"; "second"; "third"];;
would produce the output
val myPrint : string = "one: first two: second three: third"
Note that format strings in F# are specifically designed to take a statically known number of arguments, so there's not a particularly elegant way to do what you want. However, something like this should work:
let rec myPrintHelper<'a> (fmt:string) : string list -> 'a = function
| [] -> sprintf (Printf.StringFormat<_>(fmt))
| s::rest -> myPrintHelper<string -> 'a> fmt rest s
let myPrint fmt = myPrintHelper<string> fmt
myPrint "one: %s two: %s three: %s" ["first"; "second"; "third"]
This will throw an exception at runtime if the number of "%s"
es in your string doesn't match the number of strings in the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With