簡體   English   中英

在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

但是,該代碼不起作用。 這是編譯器說的:

文件“ liscie5.ml”,第10行,字符44-60:錯誤:此表達式的類型為'a列表,但期望的表達式類型為('b *'a列表)

(第10行:(Li​​st.length list_of_children)+ 1 +幫助list_of_children輸入)。

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

我看到的第一個問題是:

let (_,list_of_children) = node in

假定node的類型為'a tree 因此,它將看起來像Node (value, children) 但是這一行代碼將其視為OCaml值的通用對(a, b) 代替這樣寫會有所幫助:

let Node (_,list_of_children) = node in

有更多簡潔的方法可以編寫此代碼,但這應該會有所幫助。 毫無疑問,還有其他(可能類似)的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM