用另一个函数组合函数`Printf.sprintf`

Pte*_*mys 2 ocaml types

我有很多事情将结果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"的正确方法是什么?

cam*_*ter 8

不要用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)

  • 请注意,从4.02开始,格式字符串在内部用GADT实现,而"%s"只是"CamlinternalFormatBasics.(格式(字符串(No_padding,End_of_format),"%s"))的语法糖,因此唯一的魔法留在格式字符串的输入是格式字符串和字符串文字的类型导向消歧. (2认同)