LARA

Simple Nested Procedures

Nested functions can access outside functions.

def saveData(f : File) = {
  def wr(s : String) = {
    writeStringToFile(f, s)
  }
  def wrInt(x : Int) = {
    wr(integerToString(x))
  }
  wr("<body>")
  wr("This is my page.")
  wrInt(2008)
  wr("</body>")
}

Here function 'wr' accesses both 's' and 'f'

  • note that 'f' can be at different places relative to stack top

How does code for 'wr' access 'f' ?

Several alternative solutions:

  1. static links: pass extra 'static link' for the enclosing function ('saveData' for 'wr')
    • chase links when nesting many procedures
  2. displayes: maintain global display array of most recent procedure of static nesting depth 'i'
    • avoids chasing links
  3. lambda lifting: make enclosing function arguments explicit, eliminating nested functions
    • modifies both function definition and function call

Previous example after lambda lifting is simply:

def wr(s : String, f : File) = {
  writeStringToFile(f, s)
}
def wrInt(x : Int, f : File) = {
  wr(integerToString(x), f)
}
def saveData(f : File) = {
  wr("<body>", f)
  wr("This is my page.", f)
  wrInt(2008, f)
  wr("</body>", f)
}