[英]Depth of n-ary tree OCaml
I had to calculate the depth of a n-ary tree in OCaml using only functional paradigm whitout the use of external homemade function.我必须仅使用函数范式来计算 OCaml 中 n 元树的深度,而无需使用外部自制函数。 Here's the struc:这是结构:
type nTree =
Id of int
| Leaf of string
| Tree of string * string * nTree list
and here is my result:这是我的结果:
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)
It work but I find it very ugly and the e::r
bit cause a warning because of not matching the []
pattern.它有效,但我发现它非常丑陋,并且e::r
位由于不匹配[]
模式而导致警告。 Is there a way to make this warning free and "prettier"?有没有办法让这个警告免费且“更漂亮”?
Thx!谢谢!
the
e::r
bit causes a warning because of not matching the[]
pattern由于不匹配[]
模式,e::r
位导致警告
You'd just use pattern matching instead of if
:您只需使用模式匹配而不是if
:
match n with
| [] -> 1
| e::r -> …
But actually there's no point in distinguishing these at all.但实际上根本没有必要区分这些。 You should be doing你应该做的
let rec height = function
| Id _ -> 0
| Leaf _ -> 0
| Tree(_,_,n) -> 1 + List.fold_left max 0 (List.map height n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.