由于我使用F#进行研究(特别是使用F#interactive),我希望能够切换"print-when-in-debug"功能.
我可以
let dprintfn = printfn
Run Code Online (Sandbox Code Playgroud)
F#互动说
val dprintfn : (Printf.TextWriterFormat<'a> -> 'a)
Run Code Online (Sandbox Code Playgroud)
我可以使用
dprintfn "myval1 = %d, other val = %A" a b
Run Code Online (Sandbox Code Playgroud)
每当我想要我的脚本.
现在我想以dprintfn不同的方式定义,以便它会忽略所有与语法兼容的参数printfn.怎么样?
我想到的最接近(但不起作用)的变体是:
let dprintfn (arg: (Printf.TextWriterFormat<'a> -> 'a)) = ()
Run Code Online (Sandbox Code Playgroud)
但它以下不编译然后dprintfn "%A" "Hello"导致error FS0003: This value is not a function and cannot be applied.
PS我目前使用别名Debug.WriteLine(...)作为解决方法,但问题仍然是有趣的F#类型系统.
Tom*_*cek 11
您可以使用该kprintf函数,该函数使用标准语法格式化字符串,但随后调用您指定的(lambda)函数来打印格式化的字符串.
例如,如果debug设置了以下内容则打印字符串,否则不执行任何操作:
let myprintf fmt = Printf.kprintf (fun str ->
// Output the formatted string if 'debug', otherwise do nothing
if debug then printfn "%s" str) fmt
Run Code Online (Sandbox Code Playgroud)