[英]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
位由於不匹配[]
模式而導致警告。 有沒有辦法讓這個警告免費且“更漂亮”?
謝謝!
由於不匹配
[]
模式,e::r
位導致警告
您只需使用模式匹配而不是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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.