n叉树OCaml的深度

Depth of n-ary tree OCaml

我不得不在不使用外部自制函数的情况下仅使用函数范式来计算 OCaml 中 n 叉树的深度。这是结构:

type nTree = 
  Id of int
  | Leaf of string
  | Tree of string * string * nTree list

这是我的结果:

  let rec height t = match t with
     | Id _ -> 0
     | Leaf _ -> 0
     | Tree(_,_,n) -> if n = [] then 1
                      else let e::r = n in max 
                      (List.fold_left (fun acc x -> acc + height x) 1 [e])
                      (List.fold_left (fun acc x -> acc + height x) 1 r)

它可以工作,但我发现它非常难看,并且 e::r 位由于不匹配 [] 模式而导致警告。 有没有办法让这个警告免费和“漂亮”?

谢谢!

the e::r bit causes a warning because of not matching the [] pattern

您只需使用模式匹配而不是 if:

match n with
  | [] -> 1
  | e::r -> …

但实际上根本没有必要区分这些。你应该做

  let rec height = function
     | Id _ -> 0
     | Leaf _ -> 0
     | Tree(_,_,n) -> 1 + List.fold_left max 0 (List.map height n)