Introduction to Delimited Continuations/Handling the continuation

From Wikiversity
Jump to navigation Jump to search

Now we can start to do some neat things with the continuation. There's no reason that k has to be invoked from within the shift block. Maybe we don't want to wait for the user to input a line of text, or maybe we don't even know when or from where the input will come. In either case, we can put the continuation off to the side, so we can invoke it by some other means.

var c: String => Unit = _

def run() = reset {
  println("What is your name?")
  val name = shift { k: (String => Unit) =>
    c = k
  }
  println("Hello, " + name + "!")
}

Invoking run will stick the continuation (which in this case is everything after the shift block -- a function which takes a String and prints a message to the console) into the variable c, which we can invoke later (eg from the REPL, another function, etc.).