Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# apply sprintf to a list of strings

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"
like image 844
David Dickson Avatar asked Sep 19 '25 04:09

David Dickson


1 Answers

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.

like image 117
kvb Avatar answered Sep 22 '25 06:09

kvb