Scala: Convenience constructor,一种惰性的、不需要延迟的构造函数
Scala: Convenience construtor, a constructor that is lazy and requires no delay
我的任务是创建一个所谓的 "convenience constructor",它应该用于构建下面给出的分支的实例。对此的限制是构造函数应该是惰性的并且不应该需要任何显式延迟。
完整任务描述如下:
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 转换为无参数函数 - 但我不完全确定这是否正确,我的任何尝试都没有成功。最后,我不确定 "explicit delays" 推断出什么,但我认为这意味着评估是在每个级别进行的,而不是在找到最深的节点(并行化目的)之后进行的。
如果有人对如何使惰性而不是显式延迟有任何澄清或可能的解决方案'convenience constructor',我们将不胜感激!
def branch[A] (l: =>Tree[A], r: =>Tree[A]): Tree[A] = Branch(() => l, () => r)
我的任务是创建一个所谓的 "convenience constructor",它应该用于构建下面给出的分支的实例。对此的限制是构造函数应该是惰性的并且不应该需要任何显式延迟。 完整任务描述如下:
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 转换为无参数函数 - 但我不完全确定这是否正确,我的任何尝试都没有成功。最后,我不确定 "explicit delays" 推断出什么,但我认为这意味着评估是在每个级别进行的,而不是在找到最深的节点(并行化目的)之后进行的。
如果有人对如何使惰性而不是显式延迟有任何澄清或可能的解决方案'convenience constructor',我们将不胜感激!
def branch[A] (l: =>Tree[A], r: =>Tree[A]): Tree[A] = Branch(() => l, () => r)