What are Scala continuations and why use them?

前端 未结 7 1274
梦谈多话
梦谈多话 2020-11-30 16:58

I just finished Programming in Scala, and I\'ve been looking into the changes between Scala 2.7 and 2.8. The one that seems to be the most important is the continua

相关标签:
7条回答
  • 2020-11-30 17:41

    I found the existing explanations to be less effective at explaining the concept than I would hope. I hope this one is clear (and correct.) I have not used continuations yet.

    When a continuation function cf is called:

    1. Execution skips over the rest of the shift block and begins again at the end of it
      • the parameter passed to cf is what the shift block "evaluates" to as execution continues. this can be different for every call to cf
    2. Execution continues until the end of the reset block (or until a call to reset if there is no block)
      • the result of the reset block (or the parameter to reset() if there is no block) is what cf returns
    3. Execution continues after cf until the end of the shift block
    4. Execution skips until the end of the reset block (or a call to reset?)

    So in this example, follow the letters from A to Z

    reset {
      // A
      shift { cf: (Int=>Int) =>
        // B
        val eleven = cf(10)
        // E
        println(eleven)
        val oneHundredOne = cf(100)
        // H
        println(oneHundredOne)
        oneHundredOne
      }
      // C execution continues here with the 10 as the context
      // F execution continues here with 100
      + 1
      // D 10.+(1) has been executed - 11 is returned from cf which gets assigned to eleven
      // G 100.+(1) has been executed and 101 is returned and assigned to oneHundredOne
    }
    // I
    

    This prints:

    11
    101
    
    0 讨论(0)
提交回复
热议问题