ocaml 格式化程序和值限制

Bla*_*adt 4 ocaml string-formatting value-restriction

编辑对不起大家,我以为我的小例子已经完成,结果不是。 我做了一个新的,真的应该是!

一旦我使用格式化程序作为 Scanf 或 Printf 函数的参数,格式化程序类型就会分别绑定到输入或输出通道。有没有办法让函数采用格式化程序(或字符串)并将其用作打印和读取的格式化程序?

let fmt = format_of_string "%d,%d";;
Scanf.sscanf "2,2" fmt (fun x y -> x,y);;
fmt;;
Run Code Online (Sandbox Code Playgroud)

- : (int -> int -> int * int, Scanf.Scanning.scanbuf, '_a, (int -> int -> int * int) -> int * int, (int -> int -> int * int) -> int * int, int * int) format6 = <abstr>
Run Code Online (Sandbox Code Playgroud)

这意味着后续Printf.printf fmt 1 2;;会给出类型错误。这适用于我尝试过的每种功能format_of_stringScanf.format_from_string类似功能的组合。

例子:

module Thing = struct

(* Just a helper for file IO *)
type 'a result = Success of 'a | Failure of exn;;
let with_out_file filename fn =
  let out_ch = open_out filename in
  let res = try Success (fn out_ch) with
    exn -> Failure exn in
  close_out out_ch;
match res with
| Success a -> a
| Failure a -> raise a;;

(* Uses the format string for writing *)
let print (fmt : ('a, 'b, 'c, 'd, 'e, 'f) format6) fn v =
  with_out_file fn (fun x -> Printf.fprintf x fmt v);;

(* Uses the format string for reading *)
let read (fmt : ('a, 'b, 'c, 'd, 'e, 'f) format6) v =
  Scanf.sscanf v fmt (fun x -> x);;

(* Where things break *)
let both fmt v =
  read fmt "42\n";
  print fmt "tfile" v;;
end;;
Run Code Online (Sandbox Code Playgroud)

Error: This expression has type ('a -> 'b, Scanf.Scanning.scanbuf, 'c, ('d -> 'd) -> 'e, ('a -> 'b) -> 'f, 'f) format6 but an expression was expected of type                                                       
     ('a -> 'b, out_channel, unit, unit, unit, unit) format6                                                                                                                                                    
   Type Scanf.Scanning.scanbuf is not compatible with type out_channel
Run Code Online (Sandbox Code Playgroud)

对于both函数的最后一行,这似乎是有道理的,但是如果我both从模块中删除函数,我可以使用相同的格式字符串(与参数相同的变量)调用readprint并且它可以正常工作。

所以,希望你们还没有放弃我;我该如何解决?在这种情况下,eta 扩展和类型注释似乎都不起作用?

And*_*uer 5

您遇到了臭名昭著的价值限制

# let fmt = format_of_string "%d,%d";;
val fmt : (int -> int -> '_a, '_b, '_c, '_d, '_d, '_a) format6 = <abstr>
Run Code Online (Sandbox Code Playgroud)

那些'_a, '_b, '_c,'_d表示“尽快确定类型”。它们不是参数,即fmt不是多态值。相比之下,空列表是多态的:

# let emptiness = [] ;;
val emptiness : 'a list = []
Run Code Online (Sandbox Code Playgroud)

现在我们有'a没有 '_a。但也许你已经知道这一切。关键是当我们申请Printf.printffmt,它的类型被固定为

(int -> int -> unit, out_channel, unit, unit, unit, unit) format6
Run Code Online (Sandbox Code Playgroud)

但是当我们申请它的类型时Scanf.sscanffmt它被固定为

(int -> int -> int * int, Scanf.Scanning.in_channel, '_a,
(int -> int -> int * int) -> int * int,
(int -> int -> int * int) -> int * int, int * int)
format6
Run Code Online (Sandbox Code Playgroud)

这两种类型不兼容,并且因为fmt不是多态的,所以不能同时使用它。解决方案很简单,只需要有两个副本,fmt_in并且fmt_out. 该解决方案有什么不可接受的地方吗?