F#:用字符串组合 sprintf ->允许格式化的单位函数

发布于 2024-11-28 15:41:21 字数 378 浏览 1 评论 0 原文

有关如何对格式及其格式进行自定义处理的信息,请参阅。我想做一些更简单的事情,具体来说,我想做一些达到以下效果的事情:

let writelog : string -> unit = ... // write the string to the log

let writelogf = sprintf >> writelog // write a formatted string to the log

编译器对此感到困惑我并不感到太惊讶,但是有什么办法让它工作吗?

There's information out there on how to do custom processing on a format and its parts. I want to do something a bit simpler, specifically, I want to do something to the effect of:

let writelog : string -> unit = ... // write the string to the log

let writelogf = sprintf >> writelog // write a formatted string to the log

I'm not too surprised that the compiler gets confused by this, but is there any way to get it to work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

智商已欠费 2024-12-05 15:41:21

定义采用 printf 等格式字符串的函数的最简单方法是使用 Printf.kprintf 函数。 kprintf 的第一个参数是一个函数,用于显示格式化后的结果字符串(因此您可以将其传递给您的 writelog 函数):

let writelog (s:string) = printfn "LOG: %s" s
let writelogf fmt = Printf.kprintf writelog fmt

fmt 参数是特殊格式字符串。这比jpalmer的解决方案效果更好,因为如果您指定一些附加参数,它们将直接传递给kprintf(因此参数的数量可以取决于格式化字符串)。

你可以写:

> writelogf "Hello";;
LOG: Hello

> writelogf "Hello %d" 42;;
LOG: Hello 42

The simplest way to define your own function that takes a formatting string like printf is to use Printf.kprintf function. The first argument of kprintf is a function that is used to display the resulting string after formatting (so you can pass it your writelog function):

let writelog (s:string) = printfn "LOG: %s" s
let writelogf fmt = Printf.kprintf writelog fmt

The fmt parameter that is passed as a second argument is the special format string. This works better than jpalmer's solution, because if you specify some additional arguments, they will be directly passed to kprintf (so the number of arguments can depend on the formatting string).

You can write:

> writelogf "Hello";;
LOG: Hello

> writelogf "Hello %d" 42;;
LOG: Hello 42
执妄 2024-12-05 15:41:21

这有效

> let writelog = fun (s:string) -> printfn "%s" s;;

val writelog : string -> unit

> let writelogf arg = sprintf arg >> writelog;;

val writelogf : Printf.StringFormat<('a -> string)> -> ('a -> unit)

> writelogf "hello %s" "world";;
hello world
val it : unit = ()
>

(会话来自 FSI)

关键是 writelogf 的额外参数

This works

> let writelog = fun (s:string) -> printfn "%s" s;;

val writelog : string -> unit

> let writelogf arg = sprintf arg >> writelog;;

val writelogf : Printf.StringFormat<('a -> string)> -> ('a -> unit)

> writelogf "hello %s" "world";;
hello world
val it : unit = ()
>

(session is from FSI)

key is in the extra argument to writelogf

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文