2014-03-29 63 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'给一个名字(或多个名字)给你的递归调用返回的值。 –