4

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"

2 Answers 2

8

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.

1
  • thanks, that's exactly the kind of thing I was looking for. However, your implementation above prints the list in reverse order. Shouldn't be too hard for me to modify. Feb 1, 2011 at 13:44
0
List.map myPrint ["first"; "second"; "third;"]

Will return a new sprintf'ed List...

To just print out to console... List.iter will iterate a function over each value in a list, and perform that function - but will only work with functions that don't return a value. (i.e. printf...)

map takes an 'T -> 'U - and will convert a list of any format into any other So

let myPrint in = sprintf "%s" in

would be allowed, but reading your question again - it doesn't do what you want. - you could use mapi, which adds the index in (int -> 'T -> 'U) and would let you define myPrint as

let myPrint index val = sprintf "%d : %s" index val

Which would return ["1 : first"; "2 : second"; "3 : third"] which is getting closer...

But it looks like you want a single string returned - so either to String.Join on the output of that - or use fold:

let final = List.fold (fun (builder, index) in -> builder.AppendFormat("{0}: {1}", index, in), index + 1) (new StringBuilder()) ["first"; "second"; "third"]
1
  • how would you define myPrint to get the desired output specified above? Feb 1, 2011 at 12:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.