我必须制作一个递归函数来计算三种不同类型的二叉树的节点数,我想将它们保存在具有以下类型 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)
;;
最佳答案
我在你的代码中看到了很多问题,但如果你问一个具体的问题可能会更好。作为开始,您使用了名称 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)
关于tree - OCaml 未绑定(bind)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22733385/