[英]How can I wrap sprintf + a call into a single function, and have two signatures, in F#?
I have a function that takes a string and sends it to a terminal:我有一个 function 接受一个字符串并将其发送到终端:
Print: string -> unit
it is passed to several modules that do this, to simplify the syntax它被传递给执行此操作的几个模块,以简化语法
// printing
let print = settings.Print
and then it's used like that:然后像这样使用它:
print "hello"
print (sprintf "the time is %A" DateTime.UtcNow)
my question is: Can I make two functions, with the same name but two signatures, so I could use it to either print a string, or a sprintf, then print the string.我的问题是:我可以创建两个具有相同名称但有两个签名的函数,因此我可以使用它来打印字符串或 sprintf,然后打印字符串。 for example:例如:
print "hello"
print "the time is %A" DateTime.UtcNow
Is this possible?这可能吗? the goal is to simplify the syntax as a lot of code is peppered with info being sent to the terminal (which is currently a Telegram channel)目标是简化语法,因为许多代码都包含发送到终端的信息(目前是电报频道)
You can use kprintf
for this:您可以为此使用kprintf
:
let myPrint s = printfn "My print: %s !" s
let print x = Printf.kprintf myPrint x
print "%d" 1
print "aaaa"
print "%s %s" "b" "c"
There are some examples here and here . 这里和这里有一些例子。
I couldn't find kprintf
documentation, so I'm not sure that this usage is correct, but it produces the correct result for me.我找不到kprintf
文档,所以我不确定这种用法是否正确,但它为我产生了正确的结果。 Another possible candidate is ksprintf
, which also produces the same result.另一个可能的候选者是ksprintf
,它也产生相同的结果。
You can use the same signature as sprintf:您可以使用与 sprintf 相同的签名:
let print (format : Printf.StringFormat<'T>) =
sprintf format
|> dosomethingElse
and you can use it as you want:你可以随意使用它:
print "hello"
print "the time is %A" DateTime.UtcNow
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.