问题描述
由于我使用F#(特别是使用F#交互式)进行研究,所以我希望具有可切换的调试时打印"功能.
Since I do research with F# (in particular, using F# interactive), I'd like to have switchable "print-when-in-debug" function.
我能做
let dprintfn = printfn
F#互动说
val dprintfn : (Printf.TextWriterFormat<'a> -> 'a)
我可以使用
dprintfn "myval1 = %d, other val = %A" a b
在脚本中需要的任何时候.
whenever I want in my scripts.
现在,我想以不同的方式定义dprintfn
,以便它忽略其所有参数,但与printfn
语法兼容.怎么样?
Now I'd like to define dprintfn
differently, so that it would ignore all its arguments yet being syntax-compatible with printfn
. How?
我想到的最接近(但尚无作用)的变体是:
The closest (yet non-working) variant I have in mind is:
let dprintfn (arg: (Printf.TextWriterFormat<'a> -> 'a)) = ()
,但是下面的内容然后不编译,dprintfn "%A" "Hello"
,从而导致error FS0003: This value is not a function and cannot be applied
.
but it the following doesn't compile then dprintfn "%A" "Hello"
, resulting in error FS0003: This value is not a function and cannot be applied
.
PS .我目前使用Debug.WriteLine(...)
的别名作为解决方法,但是对于保持F#的类型系统仍然是一个有趣的问题.
P.S. I currently use an alias for Debug.WriteLine(...)
as work-around, but the question is still interesting for understading F#'s type system.
推荐答案
您可以使用kprintf
函数,该函数使用标准语法格式化字符串,然后调用您指定的(lambda)函数以打印格式化的字符串.
You can use the kprintf
function, which formats a string using the standard syntax, but then calls a (lambda) function you specify to print the formatted string.
例如,如果设置了debug
,则以下内容将打印字符串,否则不执行任何操作:
For example, the following prints the string if debug
is set and otherwise does nothing:
let myprintf fmt = Printf.kprintf (fun str ->
// Output the formatted string if 'debug', otherwise do nothing
if debug then printfn "%s" str) fmt
这篇关于如何在F#中定义printfn等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!