Dav*_*son 3 recursion f# functional-programming
我怎样才能最好地创建一个函数(让我们称之为myPrint),它将sprintf,一个格式字符串和一个字符串列表作为参数,并产生一个结果,使得字符串列表中的每个元素都被应用/折叠到sprintf中?
即
myPrint (sprintf "one: %s two: %s three: %s") ["first"; "second"; "third"];;
Run Code Online (Sandbox Code Playgroud)
会产生输出
val myPrint : string = "one: first two: second three: third"
Run Code Online (Sandbox Code Playgroud)
请注意,F#中的格式字符串专门用于获取静态已知数量的参数,因此没有特别优雅的方法来执行您想要的操作.但是,这样的事情应该有效:
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"]
Run Code Online (Sandbox Code Playgroud)
如果"%s"字符串中的es数与列表中的字符串数不匹配,则会在运行时抛出异常.