如何在F#中定义printfn等价物

boh*_*nko 7 f# f#-interactive

由于我使用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)

  • F#编译器对`printf'格式的字符串以及与之关联的类型的静态分析具有特殊的支持。kprintf是在您自己的函数中利用此功能的标准方法。 (2认同)