使用格式打印嵌套框

Printing nested boxes with Format

我正在尝试使用格式和框来实现这一点(主要是为了摆脱深度参数):

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 对齐(类似于此处描述的 problem/solution:https://discuss.ocaml.org/t/format-module-from-the-standard-library/2254/9)。执行此操作的更好方法是什么?

AFAICS,最好的解决方案是这样的:

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