Tuesday, September 29, 2009

Scala's Delimited Continuations -- A Use Case

When I first talked about the upcoming Scala 2.8 Delimited Continuations, I did not go into what uses I foresaw for them, mostly because I was pretty sure people would find uses I could never have imagined for it.

Well, people did find uses I could never have imagined, it turns out! If Scala and Distributed Computing are your things -- hell, if even one of them is your thing! -- do go check Swarm out.


  1. Oi Daniel,

    Respondi seu comment lá em: http://lucastex.com.br/2009/10/22/maravilhas-do-groovy-elvis-operator/


  2. Hello, Daniel.
    I read your article on July/4/2009 about delimited continuation of Scala, and found a question.

    In the following case, "before" was printed only once, but "after" was printed twice.
    scala> reset {
    | println("before")
    | shift{(k:Unit=>Unit)=> k();k();println("some")}
    | println("after")
    | }

    However, in the following case, "2*" and "*3" is executed both twice.
    scala> reset {
    | 2*shift{(k:Int=>Int)=>k(k(1))}*3
    | }
    res24: Int = 36

    What is the difference between the two cases? If you do not mind, pleasse explain it.

  3. The explanation is in this paragraph:

    As for the second example, though the “1 + “ looks to be to the “left” of shift, it actually gets executed after shift returns, so it is part of the function being passed to shift. You find the same situation when making tail recursive functions. If you tried “1 + recurse()”, it would not be tail recursive, because “+” would only be executed after the call to “recurse” returned.

    "2 * shift{...} * 3" is the same as "2.$times(shift{...}.$times(3))". Note that args are evaluated before a method, so the $times method is actually in the aftermath of shift, not before it.

  4. Thank you very much.

    ( k => ... k(something) ... ) {x => { before x after }}
    is actually means the following?
    before { k => ... k(something) ... }{ x => after }

  5. No, that's not it. What I am saying is that any expression which involves a shift, such as "2 * shift { ... }", is part of the after, not the before.

  6. Thank you, Daniel. I appreciate your answering my question. It really helps my understanding.

    I understand that "2*" is part of "after" because it uses the result of shift{...}.

    Then, why
    { k => k(); k(); print(2) } { x => { print(1); x; print(3)} }
    does not become as
    { print(1); print(3)} { print(1); print(3)} print(2) ?

    I wonder why the second print(1) drops. Expanded result of
    { k => k(); k(); print(2) } { x => { print(1); x; print(3)} } seems to have two print(1)...
    Is it because print(1) is "before"-part and becuase "before"-part is not a continuation?

  7. Yes, that's correct. The "before" part is not part of the continuation.