2014-03-29 61 views
3

我必須做一個遞歸函數來計算三種不同類型的二叉樹的節點數,並且我將它們保存在下面的類型爲int * int * int的結果中,我想我的推理是正確的。OCaml未綁定值

type dtree = 
     Decision of string * int * dtree * string * int * dtree 
     | Chance of string * int * dtree * string * int * dtree 
     | Outcome of int 
;; 


let rec count dt = 
    match dt with 
      Decision(choiceL, costL, l, choiceR, costR, r) -> (x+1,y,z) count l count r 
     | Chance(eventL, probL, l, eventR, probR, r) -> (x,y+1,z) count l count r 
     | Outcome value -> (x,y,z+1) 

;; 

回答

1

我在代碼中看到很多問題,但是如果您問了一個特定的問題,可能會更好。作爲一個開始的地方,您使用的名稱爲x,yz,而無需在任何地方定義它們。

我認爲您的問題的關鍵在於您需要爲遞歸調用count lcount r返回的值賦予名稱。一旦他們有了名字,你可以在樹的當前級別的結果中使用它們。

更新

下面是成對列表加起來值的功能。它與您正在尋找的粗略結構相同:

let rec sumpairs pairs = 
    match pairs with 
    | [] -> (0, 0) 
    | (x, y) :: tail -> 
     let (subx, suby) = sumpairs tail in 
     (subx + x, suby + y) 
+0

如何在指定的函數中定義變量? – MMrj

+0

使用'let'給一個名字(或多個名字)給你的遞歸調用返回的值。 –