如何在F#中定义printfn等效项

编程入门 行业动态 更新时间:2024-10-19 22:25:39
本文介绍了如何在F#中定义printfn等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

由于我使用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等效项

本文发布于:2023-11-10 02:36:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574100.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:定义   如何在   printfn

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!