What is the preferred way to implement 'yield' in Scala?

前端 未结 3 1346
轻奢々
轻奢々 2021-01-31 19:23

I am doing writing code for PhD research and starting to use Scala. I often have to do text processing. I am used to Python, whose \'yield\' statement is extremely useful for i

3条回答
  •  你的背包
    2021-01-31 19:52

    'yield' sucks, continuations are better

    Actually, Python's yield is a continuation.

    What is a continuation? A continuation is saving the present point of execution with all its state, such that one can continue at that point later. That's precisely what Python's yield, and, also, precisely how it is implemented.

    It is my understanding that Python's continuations are not delimited, however. I don't know much about that -- I might be wrong, in fact. Nor do I know what the implications of that may be.

    Scala's continuation do not work at run-time -- in fact, there's a continuations library for Java that work by doing stuff to bytecode at run-time, which is free of the constrains that Scala's continuation have.

    Scala's continuation are entirely done at compile time, which require quite a bit of work. It also requires that the code that will be "continued" be prepared by the compiler to do so.

    And that's why for-comprehensions do not work. A statement like this:

    for { x <- xs } proc(x)
    

    If translated into

    xs.foreach(x => proc(x))
    

    Where foreach is a method on xs's class. Unfortunately, xs class has been long compiled, so it cannot be modified into supporting the continuation. As a side note, that's also why Scala doesn't have continue.

    Aside from that, yes, this is a duplicate question, and, yes, you should find a different way to write your code.

提交回复
热议问题