F # apply sprintf to a list of strings

How can I best create a function (myPrint is called) that takes sprintf, a format string and a list of strings as arguments and produces a result so that every element in the list of strings is applied / complex in sprintf

i.e.

myPrint (sprintf "one: %s two: %s three: %s") ["first"; "second"; "third"];;

will produce output

val myPrint : string = "one: first two: second three: third"
+3
source share
2 answers

Note that format strings in F # are specifically designed to accept a statically known number of arguments, so there is no 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 a runtime exception if the number "%s"es in your line does not match the number of lines in the list.

+8
List.map myPrint ["first"; "second"; "third;"]

sprintf'ed...

... List.iter , , . (.. printf...)

'T → ' U - ,

let myPrint in = sprintf "%s" in

, - , . - mapi, (int → 'T → ' U) myPrint

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

[ "1: "; "2: "; "3: " ], ...

, - String.Join - fold:

let final = List.fold (fun (builder, index) in -> builder.AppendFormat("{0}: {1}", index, in), index + 1) (new StringBuilder()) ["first"; "second"; "third"]
0

Source: https://habr.com/ru/post/1789207/


All Articles