Shift / Reset

Lamora
Neuling
Neuling
Beiträge: 5
Registriert: 21. Jun 2013 17:33

Shift / Reset

Beitrag von Lamora »

Hello,

can anyone explain to me the result of the last example in V6.pdf / slide 87?
Also my question about tail calls is still open, if anyone cares to answer.

Thanks in advance

f_jakob
Mausschubser
Mausschubser
Beiträge: 50
Registriert: 27. Okt 2009 14:05

Re: Shift / Reset

Beitrag von f_jakob »

Hi Lamora,

the code in question:

Code: Alles auswählen

import scala.util.continuations._

object Main extends App {
  def foo() = { 1 + shift{k: (Int=>Int) => k(k(k(7)))}}
  def bar() = {foo() * 2}
  def baz() = { reset{bar() + 10} }
  println(baz())
}
You can get the result by compiling the code with the -P:continuations:enable flag:

Code: Alles auswählen

$ scalac -P:continuations:enable code.scala
$ scala Main
140
What happens is the following:

Everytime the continuation k is called, the execution will jump to the beginning of the reset block and process it, but will replace the switch block with the applied argument. The result of the call to the continuation is the result of the reset block.

Sketched out evaluation of k(7):

Code: Alles auswählen

baz()
reset{bar() + 10}
reset{{foo() * 2} + 10}
reset{{{1 + shift{k: (Int=>Int) => k(7)}} * 2} + 10}
reset{{{1 + 7}} * 2} + 10}
reset{{8 * 2} + 10}
reset{16 + 10}
26
But you actually have the nested calls to k, so the call to k(7) will be replaced by 26, which then yields a call to k(26), which yields a call to k(64), which is the result of your reset block.

Code: Alles auswählen

baz()
reset{bar() + 10}
reset{{foo() * 2} + 10}
reset{{{1 + shift{k: (Int=>Int) => k(k(k(7)))}} * 2} + 10}
reset{{{1 + shift{k: (Int=>Int) => k(k(26))}} * 2} + 10}
reset{{{1 + shift{k: (Int=>Int) => k(64)}} * 2} + 10}
reset{{{1 + 64}} * 2} + 10}
reset{{65 * 2} + 10}
reset{130 + 10}
140
Hope that helps.

Note: It is hard to visualize what is actually going on, so do not focus too much on this evaluation notation.

Lamora
Neuling
Neuling
Beiträge: 5
Registriert: 21. Jun 2013 17:33

Re: Shift / Reset

Beitrag von Lamora »

Wow perfect explanation, I wouldn't have figured this out in a thousand years. Many thanks.

Antworten

Zurück zu „Archiv“