Search code examples
scalafunctional-programmingdelaylazy-evaluation

Scala: Convenience construtor, a constructor that is lazy and requires no delay


I have been given the task to create a so-called "convenience constructor" which should serve the purpose of constructing an instance of the below-given Branch. The constraints to this are that the constructor should be lazy and should not require any explicit delays. The full task is described in the following bit:

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

}

My assumption is that I am supposed to somehow transform l and r into parameter-less functions - but I am not entirely sure if that's right nor have any of my attempts succeeded. Lastly I am not sure what is inferred by "explicit delays", but I presume it means that evaluation is done at each level rather than after finding the deepest nodes (a parallelization purpose).

If anyone has any clarifications or possible solutions to how to make a lazy and not explicitly delayed 'convenience constructor', it would be highly appreciated!


Solution

  • def branch[A] (l: =>Tree[A], r: =>Tree[A]): Tree[A] = Branch(() => l, () => r)