2017-03-08 21 views
0

我有遞歸函數,當然樹如何通過遞歸函數的值樹

type tree = Node of bool ref * (char * tree) list ref 

type cours= tree ->char list -> char list* char list * tree 

let cours t word= 
let rec cours_tree t word l1 l2=match t,word with 
    | Noeud(r,n),[] -> Noud (r,n), l1 , l2 
    | Noeud (r,n),x::h when (List.mem_assoc x !n) -> 
       x::l1,cours_tree (List.assoc x !n) h l1 l2 
    | Noeud (r,{content=(c,b)::n),x::h -> 
       x::l2,cours_tree (List.assoc x b) h l1 l2 
in 
cours_tree t word [] [] 

我希望它可以從人物的特定列表瀏覽樹的分支,並返回子樹到達,人物名單和那些無法到達的人的名單; 但我發現了一個錯誤:

Error: This expression has type char list * 'a 
     but an expression was expected of type 'a 
     The type variable 'a occurs inside char list * 'a# 

我不知道哪裏是我的問題。

+1

你爲什麼要取消IVG的編輯?這個'Noud'是什麼?如果我把它改成'Noeud',我沒有你的錯誤,我有一個語法錯誤:'Syntax error:pattern expected' here:'Noeud(r,{content =(c,b):: n),' 。 請編輯你的代碼,這樣人們可以得到你有錯誤,如果你想要一個答案。 – Lhooq

回答

0

存在諸多問題:

  1. NoudNoeud是不確定的構造函數。
  2. 無法匹敵{當您嘗試在ref上進行模式匹配時。
  3. 首先match大小寫返回tree * list * list但其他情況 返回無限類型。
  4. 錯誤ref模式匹配語法。 content應該是contents
  5. 在第二個List.assoc中輸入錯誤。 btree,但預期類型爲(char * 'a) list的表達式。

下面的代碼即可解決問題,並同時編譯,但隨着問題描述你給不完整將無法正常運行:

type tree = Node of bool ref * (char * tree) list ref 

type cours = tree -> char list -> char list * char list * tree 

let cours t word = 
    let rec cours_tree t word l1 l2 = 
    match t, word with 
    | Node (r, n), [] -> Node (r, n), l1, l2 
    | Node (r, n), x::h when List.mem_assoc x !n -> 
     let t', l1', l2' = cours_tree (List.assoc x !n) h l1 l2 in 
     t', x::l1', l2' 
    | Node (r, {contents = (c, b)::n}), x::h -> 
     let t', l1', l2' = cours_tree (List.assoc x n) h l1 l2 in 
     t', l1', x::l2' 
    in cours_tree t word [] []