问题描述
我正在尝试通过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