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

编程入门 行业动态 更新时间:2024-10-19 16:36:41
本文介绍了如何在 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:37:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574103.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:等价物   定义   如何在   printfn

发布评论

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

>www.elefans.com

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