【发布时间】:2013-02-12 14:01:37
【问题描述】:
fighting with f# - 战斗在 Trees 领域 - 专门计算节点的数量。这真的很有趣,因为我想最终用 F# 编写的程序涉及多路树,不幸的是它的开始有点麻烦 - 我希望你能提供帮助!
99 f# 系列的第 61 题,要求计算二叉树的叶子。解决方案(如下所示)计算节点,但我的问题不理解
双递归的工作原理向左循环(有趣的 lacc -> 向右循环..)
cont (branchF x lacc racc)是什么,我的印象是 cont 是“abc”函数,但这只需要两个参数...loop t idid 的类型为 unit - 我不明白这是如何暗示的
基本上不理解这一点,或者它在树中流动的顺序(调试和单步执行没有帮助)如果有更简单的示例、预读建议等,请指导我。
非常感谢您的帮助,有问题的解决方案代码如下:
干杯
td
type 'a Tree = Empty | Branch of 'a * 'a Tree * 'a Tree
let foldTree branchF emptyV t =
let rec loop t cont =
match t with
| Empty ->
cont emptyV
| Branch (x, left, right) ->
loop left (fun lacc ->
loop right (fun racc ->
cont (branchF x lacc racc)))
loop t id
let counLeaves tree =
foldTree (fun abc lc rc ->
if lc + rc = 0 then 1
else 1 + lc + rc) 0 tree
let Tree1 = Branch ('x', Branch ('x', Empty, Empty),Branch ('x', Empty, Branch ('x', Empty, Branch ('x', Empty, Empty))))
let result = counLeaves Tree1
【问题讨论】:
-
我不知道我在写解决方案时在想什么,但是 Lee 是 wright 并且 counLeaves 中的“if”没有任何作用。解决方案应该是 let counLeaves tree = tree |> foldTree (fun _ lc rc -> 1 + lc + rc) 0。如果你想了解更多关于折叠和延续的信息。我推荐这里link 的 Brian McNamara 的变形论系列。这就是我得到 fodlTree 函数的地方。
-
嗨,Cesar,我只想说感谢您发布 99 个问题系列 - 非常棒的学习工具 - 特别是多种解决方案。干杯!
-
鉴于没有人回答您关于 id 的问题,“id”是身份运算符。您可以将 id 替换为 (fun x -> x) 以获得相同的效果。见这里:msdn.microsoft.com/en-us/library/ee353607.aspx 另外,这段代码有一些非常错误的地方——我创建了一个简单的 4 节点树,它告诉我大小是 32!一旦弄清楚所有细微差别,我将发布正确的实现(我正在工作)。
标签: recursion f# tree continuations