Note that there are some explanatory texts on larger screens.

plurals
  1. POContinuations and for comprehensions -- what's the incompatibility?
    primarykey
    data
    text
    <p>I am new to Scala and trying to wrap my head around continuations I'm trying to reproduce the <code>yield return</code> C# statement.</p> <p>Following <a href="https://stackoverflow.com/a/2655394/116301">this post</a>, I have written the following code :</p> <pre><code>package com.company.scalatest import scala.util.continuations._; object GenTest { val gen = new Generator[Int] { def produce = { yieldValue(1) yieldValue(2) yieldValue(3) yieldValue(42) } } // Does not compile :( // val gen2 = new Generator[Int] { // def produce = { // var ints = List(1, 2, 3, 42); // // ints.foreach((theInt) =&gt; yieldValue(theInt)); // } // } // But this works? val gen3 = new Generator[Int] { def produce = { var ints = List(1, 2, 3, 42); var i = 0; while (i &lt; ints.length) { yieldValue(ints(i)); i = i + 1; } } } def main(args: Array[String]): Unit = { gen.foreach(println); // gen2.foreach(println); gen3.foreach(println); } } abstract class Generator[E] { var loopFn: (E =&gt; Unit) = null def produce(): Unit @cps[Unit] def foreach(f: =&gt; (E =&gt; Unit)): Unit = { loopFn = f reset[Unit, Unit](produce) } def yieldValue(value: E) = shift { genK: (Unit =&gt; Unit) =&gt; loopFn(value) genK(()) () } } </code></pre> <p>As you can see, <code>gen2</code> is commented out as it does not compile. Since I can easily iterate over the content of a list using a while loop (see <code>gen3</code>), I expected the foreach loop to work just as well.</p> <p>The compilation error is the following :</p> <pre><code>no type parameters for method foreach: (f: Int =&gt; B)Unit exist so that it can be applied to arguments (Int =&gt; Unit @scala.util.continuations.cpsParam[Unit,Unit]) --- because --- argument expression's type is not compatible with formal parameter type; found : Int =&gt; Unit @scala.util.continuations.cpsParam[Unit,Unit] required: Int =&gt; ?B </code></pre> <p><strong>Why do I get this error and is there a way to work around this with something cleaner than a while loop?</strong></p> <p>Thank you</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload