编辑:对不起大家,我以为我的小考试已经完成,结果不是。 我做了一个新的,真的应该是!
一旦我将格式化程序用作 Scanf 或 Printf 函数的参数,格式化程序类型就会分别绑定到输入或输出通道。有没有办法让函数采用格式化程序(或字符串)并将其用作打印和阅读的格式化程序?
let fmt = format_of_string "%d,%d";;
Scanf.sscanf "2,2" fmt (fun x y -> x,y);;
fmt;;
给
- : (int -> int -> int * int, Scanf.Scanning.scanbuf, '_a, (int -> int -> int * int) -> int * int, (int -> int -> int * int) -> int * int, int * int) format6 = <abstr>
这意味着后续Printf.printf fmt 1 2;;
会给出类型错误。这适用于我尝试过
的每种功能组合format_of_string
和类似功能。Scanf.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;;
给
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
对于both
函数的最后一行,这似乎是有道理的,但如果我both
从模块中删除函数,我可以使用相同的格式字符串(与参数相同的变量)调用read
和,它就可以工作。print
所以,希望你们还没有放弃我;我该如何解决?在这种情况下,eta-expansion 和类型注释似乎都不起作用?