我被赋予了创建所谓的“便利构造函数”的任务,该构造函数应该用于构造下面给定的分支的实例。对此的约束是构造函数应该是惰性的,不应该要求任何明确的延迟。 完整任务在以下位中描述:
object Q5 {
/**
* Task 5.
*
* Consider a type of lazy binary trees:
*/
trait Tree[+A]
case class Branch[+A] (l:() => Tree[A], r:() => Tree[A]) extends Tree[A]
case object Leaf extends Tree[Nothing]
/**
* Implement a convenience constructor 'branch' that is both lazy
* but does not require using explicit delays like Branch.
*/
def branch[A] (l : =>Tree[A], r: =>Tree[A]) :Tree[A] = //TODO: Solve this
}
我的假设是我应该以某种方式将l和r转换为无参数函数 - 但我不完全确定这是否正确,也没有任何尝试成功。最后我不确定“显式延迟”是什么推断,但我认为这意味着评估是在每个级别完成的,而不是在找到最深的节点之后(并行化目的)。
如果有人有任何澄清或可能的解决方案如何制作一个懒惰而没有明确延迟的'便利构造函数',我们将非常感谢!
答案 0 :(得分:2)
def branch[A] (l: =>Tree[A], r: =>Tree[A]): Tree[A] = Branch(() => l, () => r)