LARA

Simple Implementations of Lazy Evaluation

Explicit Check

Replace

x = f(p,q)
y = g(x)
 
def g(y) = {
  y + 1
}

with

x = Thunk(_ => f(p,q))
y = g(x)
 
def g(y) = {
  y.get()+1
}

where

class Thunk[A](var toCompute : Unit => A)
  var res : A = _
  var computed : Boolean = false
  def get : A = {
    if (computed)
      res
    else {
      res = toCompute()
      computed = true
    }
  }
}

Function Pointer Overriding

Replaces if-then-else check in get with dynamically patching the code to be called once the value is computed

class Thunk[A](toCompute : Unit => A) {
  var res : A
  var get : (Unit => A) = computeAndReturn
 
  def computeAndReturn(_ : Unit) : A = {
     res = toCompute()
     get = returnComputed
  }
 
  def returnComputed(_ : Unit) : A = { res }
}