【问题标题】:regular shaped tree fold left scala implementation规则形状的树折叠左scala实现
【发布时间】:2020-04-13 06:09:07
【问题描述】:

我正在尝试为规则形状的树实现尾递归 foldLeft 函数。该练习来自练习 3.3.5.3 中的“The Science of Functional Programming”一书。

到现在为止,我可以做这些练习,但我不知道我在这个练习中缺少什么。

规则形状的树有一个定义:

sealed trait RTree[A]
final case class Leaf[A](x: A) extends RTree[A]
final case class Branch[A](xs: RTree[(A,A)]) extends RTree[A]

方法签名和预期结果:

@tailrec
def foldLeft[A,R](t: RTree[A])(init: R)(f: (R,A)=>R): R= ???

foldLeft(Branch(Branch(Leaf(((1,2),(3,4))))))(0)(_+_)
//10

目前最大的问题是我不知道如何匹配和访问Branch的case类里面的元素。我只能匹配LeafBranch(而不是分支内的叶子),因此递归没有结束。

【问题讨论】:

    标签: scala recursion functional-programming tree


    【解决方案1】:

    不确定这是否有帮助,但目前我只有非尾递归实现。

    def foldLeft[A, R](t: RTree[A])(init: R)(f: (R, A) => R): R = {
          t match {
            case Leaf(value) => f(init, value)
            case Branch(tree) =>
              foldLeft(tree)(init) {
                case (result, (left, right)) => f(f(result, left), right)
              }
          }
        }
    

    更新:正如 cmets 部分对这个答案所说,这实际上是 tail rec 实现,对不起,让你感到困惑。

    【讨论】:

    • 你错了。这 尾递归的。 (也就是说你的答案是对的。)
    • 对不起,请-我已尝试使用@tailrec 编译此代码-但 scalac 表示无法优化此方法。我的 Scala 版本 - 2.12.6
    • @jwvh 好的,非常感谢您的帮助,如果您不介意,我会更新答案。
    猜你喜欢
    • 2020-12-14
    • 2017-04-11
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    相关资源
    最近更新 更多