Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it matter where a shift stands in a reset block?

Suppose, there is a reset block with a single shift:

val r = reset { 
   // do smth. 1
   shift {...}
   // do smth. 2
   // do smth. 3
}

Is it correct that I place the shift after "do smth. 2" or "do smth. 3" without changing the result r? Is it correct that it does not matter where shift stands in a reset block?

like image 880
Michael Avatar asked Feb 24 '23 01:02

Michael


2 Answers

It highly depends on what you are making within shift. If you just calling provided function like this: shift((k: Unit => Unit) => k(Unit)) then, in your particular example, it really doesn't matter where shift stands.

Shift function just captures code that comes after it in other function (in my example this function is called k). In other words, this code:

val r = reset { 
   // do smth. 1
   shift((k: Unit => Unit) => k(Unit))
   // do smth. 2
   // do smth. 3
}

would be rewritten by compiler in something like this (this code just demonstrates general idea and it's not supposed to show what compiler plugin will actually generate):

val k = (Unit => Unit) => {
    // do smth. 2
    // do smth. 3
} 

val r = { 
   // do smth. 1
   k(Unit)
}

But if you have some logic inside shift, like conditional k execution, then it really matters where this shift stands.

Hope this helps (and I hope, that I understood your question correctly)

like image 52
tenshi Avatar answered Mar 04 '23 20:03

tenshi


Just adding to the answer already given, the place where you CAN move around shift is whether to have code before the shift or have it inside the function you pass to shift:

reset { 
  foo(); bar();
  shift { k => stuff }
  baz()
}

is the same as

reset {
  foo();
  shift { k => bar(); stuff }
  baz()
}
like image 29
hzap Avatar answered Mar 04 '23 22:03

hzap