2016-02-09 117 views
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).

任何想法我的代碼有什麼問題?

+0

你應該學習和使用'List.fold_left'。我建議使用'List.fold_left'重新實現'List.length',然後修改它以解決您的問題。 –

回答

2

第一個問題,我看到的是:

let (_,list_of_children) = node in 

想必node'a tree類型。因此它看起來像Node (value, children)。但是這行代碼將它視爲一個通用的OCaml值對(a, b)。這將有助於代之以:

let Node (_,list_of_children) = node in 

有更簡潔的方式來寫這個,但它應該有助於取得一點進展。毫無疑問,還有其他(可能類似的)問題。