【发布时间】:2015-12-09 01:48:41
【问题描述】:
我正在为如何为仿函数内使用的类型安装打印机功能而苦苦挣扎。结构有点像这样:
module Input : sig
type t
val print fmt arg : Format.formatter -> t -> unit
end
module type INPUT = module type of Input
module F (I:INPUT) : sig
val foo : I.t -> unit
end
现在我想打印在F.foo 中使用的Input.t 类型的值。我可以使用load_printer 和install_printer Input.print 为Input.t 成功安装打印机,但是从F (Input) 内部打印时,它无法识别出正确的类型。
根据要求,这里是一个独立的示例。应该在打开调试的情况下构建它,然后在调试器中使用load_printer 加载.cmo。
module type INPUT = sig
type t
val print : Format.formatter -> t -> unit
val to_list : t -> int list
val of_list : int list -> t
end
module V1 : INPUT = struct
type t = int
let print fmt i = Format.fprintf fmt "%d" i
let to_list i = [i]
let of_list = function [i] -> i | _ -> raise @@ Failure ""
end
module V2 : INPUT = struct
type t = int * int
let print fmt (i, j) = Format.fprintf fmt "%d, %d" i j
let to_list (i, j) = [i; j]
let of_list = function [i; j] -> (i, j) | _ -> raise @@ Failure ""
end
module F (V:INPUT) = struct
let ssquare v = (V.to_list v)
|> List.map (fun i -> i * i)
|> List.fold_left (+) 0
let print fmt v =
let open Format in
print_string "<";
V.to_list v |> List.iter print_int;
print_string ">"
end
module F2 = F (V2);;
let v2 = V2.of_list [2;4] in
let _ = Format.fprintf Format.std_formatter "%a\n" F2.print v2 in
let _ = F2.ssquare v2 in
()
这个程序可以很好地打印值v2。但是,调试时实际上存在两个问题。我可以install_printer V2.print,但是当将调试器放在ssquare 函数中并调用print v2 时,它不会打印出来。此外,我什至不知道如何安装函子中定义的print。
【问题讨论】:
-
这似乎是一个经常会遇到的问题,但我只发现了一篇关于它的旧邮件列表帖子而没有答案?
-
没有多少人使用 ocamldebug,仅供参考。
-
如果您提供实际编译的代码,这将有助于我集中注意力。我不想花太多时间思考与您所问的问题不同的问题 :-) 另一方面,如果上次没有人回答,很可能没有好的答案。
-
@EdgarAroutiounian 您可以在 OCaml 顶层安装打印机(不仅仅是 ocamldebug)。我发现它在过去很有用;有时有一个大值的简单表示法。
-
@JeffreyScofield 我更新了问题(不知道这是否会自动向评论者发送通知)
标签: debugging ocaml pretty-print