1
我正在編寫一個應該計算ocaml中給定樹中節點數的程序。計算ocaml中樹中的節點數
type 'a tree = Node of 'a * 'a tree list
let count tree =
let rec visit node =
let (_,list_of_children) = node in
let rec help list1 =
match list1 with
| [] -> 0
| h::t -> (help t) + (visit h) in
(List.length list_of_children) + 1 + help list_of_children in
visit tree
但是,代碼不起作用。以下是編譯器所說的內容:
File "liscie5.ml", line 10, characters 44-60: Error: This expression has type 'a list but an expression was expected of type ('b * 'a list) list
(Line 10: (List.length list_of_children) + 1 + help list_of_children in).
任何想法我的代碼有什麼問題?
你應該學習和使用'List.fold_left'。我建議使用'List.fold_left'重新實現'List.length',然後修改它以解決您的問題。 –