我有很多事情将结果Printf.sprintf插入到另一个函数中(比方说)f.我一直试图定义printf这两者的组成,如下所示:
let printf : 'a 'b. ('a,unit,string) format -> 'b =
(fun fmt -> Printf.sprintf fmt) |> f
Run Code Online (Sandbox Code Playgroud)
但是,这并不是类似的,并且它的版本也没有几个应用程序Obj.magic.获得这样一个"自定义printf"的正确方法是什么?
不要用Obj.magic.
由于格式字符串的特殊输入实现了可变参数printf,你不能使用简单的函数组合来编写这样的东西:
let sprintf_then_f fmt args ... = f (Printf.sprintf fmt args ...)
Run Code Online (Sandbox Code Playgroud)
为了克服这个困难,在诸如的名称中Printf提供具有k(kontinuation)的连续样式函数Printf.ksprintf.请使用它们:
val ksprintf : (string -> 'd) -> ('a, unit, string, 'd) format4 -> 'a
(** Same as [sprintf] above, but instead of returning the string,
passes it to the first argument.
@since 3.09.0
*)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
87 次 |
| 最近记录: |