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',然后修改它以解决您的问题。 –