计算ocaml中树中的节点数
Counting number of nodes in tree in 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).
知道我的代码有什么问题吗?
我看到的第一个问题是:
let (_,list_of_children) = node in
推测 node
是 'a tree
类型。因此它看起来像 Node (value, children)
。但是这行代码将其视为一对通用的 OCaml 值 (a, b)
。改为这样写会有所帮助:
let Node (_,list_of_children) = node in
这个还有更简洁的写法,不过应该能进步一点吧。毫无疑问还有其他(可能类似)的问题。
我正在编写一个程序,该程序应该计算 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).
知道我的代码有什么问题吗?
我看到的第一个问题是:
let (_,list_of_children) = node in
推测 node
是 'a tree
类型。因此它看起来像 Node (value, children)
。但是这行代码将其视为一对通用的 OCaml 值 (a, b)
。改为这样写会有所帮助:
let Node (_,list_of_children) = node in
这个还有更简洁的写法,不过应该能进步一点吧。毫无疑问还有其他(可能类似)的问题。