Soy nuevo en Scala y trato de ajustarme a las continuas Estoy intentando reproducir la declaración yield return
C#.Continuaciones y para comprensión - ¿Cuál es la incompatibilidad?
Siguiendo this post, he escrito el siguiente código:
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) => yieldValue(theInt));
// }
// }
// But this works?
val gen3 = new Generator[Int] {
def produce = {
var ints = List(1, 2, 3, 42);
var i = 0;
while (i < 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 => Unit) = null
def produce(): Unit @cps[Unit]
def foreach(f: => (E => Unit)): Unit = {
loopFn = f
reset[Unit, Unit](produce)
}
def yieldValue(value: E) =
shift { genK: (Unit => Unit) =>
loopFn(value)
genK(())
()
}
}
Como se puede ver, gen2
esté comentada, ya que no se compila. Como puedo iterar fácilmente sobre el contenido de una lista usando un ciclo while (ver gen3
), esperaba que el bucle foreach funcionara igual de bien.
El error de compilación es la siguiente:
no type parameters for method foreach: (f: Int => B)Unit exist so that
it can be applied to arguments (Int => Unit @scala.util.continuations.cpsParam[Unit,Unit])
--- because ---
argument expression's type is not compatible with formal parameter type;
found : Int => Unit @scala.util.continuations.cpsParam[Unit,Unit]
required: Int => ?B
¿Por qué aparece este error y hay una manera de evitar esto con algo más limpio que un bucle while?
Gracias
posible duplicado de [Implementar el rendimiento (retorno de rendimiento) utilizando las continuaciones de Scala] (http: // stackoverflow.com/questions/2201882/implementation-yield-yield-return-using-scala-continuations) –
No estoy buscando una respuesta que me diga cómo reproducir el "retorno de rendimiento" con las continuas de Scala. Estoy buscando la razón por la cual el 'gen2' en mi ejemplo no funciona. El 'retorno de rendimiento' es solo el contexto en el que encontré este problema. – GuiSim
Ah, lo siento entonces. –