如何在 F# 中定义 printfn 等价物 [英] How to define printfn equivalent in F#
问题描述
由于我使用 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 等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!