如何解决使用格式打印嵌套框
我正在尝试通过Format和Box实现这一点(主要是为了摆脱depth参数):
let rec spaces n =
match n with
| 0 -> ""
| n -> " " ^ spaces (n - 1)
let rec fact n d =
Format.printf "%sinput: %d\n" (spaces d) n;
let r = match n with 0 -> 1 | n -> n * fact (n - 1) (d + 1) in
Format.printf "%soutput: %d\n" (spaces d) r;
r
let () = Format.printf "%d@." (fact 5 0)
input: 5
input: 4
input: 3
input: 2
input: 1
input: 0
output: 1
output: 1
output: 2
output: 6
output: 24
output: 120
据我所知:
let rec fact n =
(* alternative,seems equivalent *)
(* Format.printf "input: %d@;<0 2>@[<v>" n; *)
Format.printf "@[<v 2>input: %d@," n;
let r = match n with 0 -> 1 | n -> n * fact (n - 1) in
Format.printf "@]@,output: %d@," r;
r
let fact n =
Format.printf "@[<v>";
let r = fact n in
Format.printf "@]";
r
let () = Format.printf "%d@." (fact 5)
input: 5
input: 4
input: 3
input: 2
input: 1
input: 0
output: 1
output: 1
output: 2
output: 6
output: 24
output: 120
我无法摆脱其他换行符。需要@,
之后的input
中断提示,或者输入全部在一行上。如果删除output
之前的中断提示,则会得到以下提示:
input: 5
input: 4
input: 3
input: 2
input: 1
input: 0
output: 1 <-- misaligned
output: 1
output: 2
output: 6
output: 24
output: 120
这很接近,但是现在output
的缩进不再与它们的input
对齐(此处描述了类似的问题/解决方案:https://discuss.ocaml.org/t/format-module-from-the-standard-library/2254/9)。有什么更好的方法?
解决方法
非洲,最好的解决方案是这样的:
let rec fact n =
Format.printf "@[<v>@[<v 2>input: %d" n;
let r = match n with
| 0 -> 1
| n -> Format.printf "@,"; n * fact (n - 1)
in
Format.printf "@]@,output: %d@]" r;
r
如果您不想触摸计算部分(例如,将其参数化),并且可以适应前导新行:
let rec fact n =
Format.printf "@,@[<v>@[<v 2>input: %d" n;
let r = match n with 0 -> 1 | n -> n * fact (n - 1) in
Format.printf "@]@,output: %d@]" r;
r
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。