我必须建立一个递归函数来计算三种不同类型的二叉树的节点数,并且我打算用下面的int * int * int类型保存它们,我认为我的推理是正确的。
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)
;;发布于 2014-03-29 16:23:46
我在您的代码中看到了许多问题,但是如果您问一个特定的问题,可能会更好。作为一个起点,您使用的是名称x、y和z,而不需要在任何地方定义它们。
我认为,解决问题的关键是,您需要给递归调用count l和count r返回的值命名。一旦它们有了名称,就可以在树的当前级别的结果中使用它们。
更新
下面是一个函数,它将值相加成对列表。它的结构与你想要的一样粗糙:
let rec sumpairs pairs =
match pairs with
| [] -> (0, 0)
| (x, y) :: tail ->
let (subx, suby) = sumpairs tail in
(subx + x, suby + y)https://stackoverflow.com/questions/22733385
复制相似问题