diff options
author | Aleksandar Prokopec <aleksandar.prokopec@gmail.com> | 2011-12-07 14:53:37 +0100 |
---|---|---|
committer | Aleksandar Prokopec <aleksandar.prokopec@gmail.com> | 2011-12-07 14:53:37 +0100 |
commit | 014a13d2be634bb3ab3468d0c071a9a870a9a9b0 (patch) | |
tree | 491ad18ca796a70b34be1d4732b80c371bfd650d /test/pending/run/reify_lazyevaluation.scala | |
parent | a36175feb5bfce59909fa4f3d9d5df6753b6ee3a (diff) | |
parent | 332fec96e31840878bed41dd7b5314b97d8da7c2 (diff) | |
download | scala-014a13d2be634bb3ab3468d0c071a9a870a9a9b0.tar.gz scala-014a13d2be634bb3ab3468d0c071a9a870a9a9b0.tar.bz2 scala-014a13d2be634bb3ab3468d0c071a9a870a9a9b0.zip |
Merge branch 'master' of https://github.com/scala/scala into execution-context
Diffstat (limited to 'test/pending/run/reify_lazyevaluation.scala')
-rw-r--r-- | test/pending/run/reify_lazyevaluation.scala | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/test/pending/run/reify_lazyevaluation.scala b/test/pending/run/reify_lazyevaluation.scala new file mode 100644 index 0000000000..f38af76751 --- /dev/null +++ b/test/pending/run/reify_lazyevaluation.scala @@ -0,0 +1,65 @@ +import scala.tools.nsc.reporters._ +import scala.tools.nsc.Settings +import reflect.runtime.Mirror.ToolBox + +object Test extends App { + val code = scala.reflect.Code.lift{ + object lazyLib { + + /** Delay the evaluation of an expression until it is needed. */ + def delay[A](value: => A): Susp[A] = new SuspImpl[A](value) + + /** Get the value of a delayed expression. */ + implicit def force[A](s: Susp[A]): A = s() + + /** + * Data type of suspended computations. (The name froms from ML.) + */ + abstract class Susp[+A] extends Function0[A] + + /** + * Implementation of suspended computations, separated from the + * abstract class so that the type parameter can be invariant. + */ + class SuspImpl[A](lazyValue: => A) extends Susp[A] { + private var maybeValue: Option[A] = None + + override def apply() = maybeValue match { + case None => + val value = lazyValue + maybeValue = Some(value) + value + case Some(value) => + value + } + + override def toString() = maybeValue match { + case None => "Susp(?)" + case Some(value) => "Susp(" + value + ")" + } + } + } + + import lazyLib._ + + val s: Susp[Int] = delay { println("evaluating..."); 3 } + + println("s = " + s) // show that s is unevaluated + println("s() = " + s()) // evaluate s + println("s = " + s) // show that the value is saved + println("2 + s = " + (2 + s)) // implicit call to force() + + val sl = delay { Some(3) } + val sl1: Susp[Some[Int]] = sl + val sl2: Susp[Option[Int]] = sl1 // the type is covariant + + println("sl2 = " + sl2) + println("sl2() = " + sl2()) + println("sl2 = " + sl2) + }; + + val reporter = new ConsoleReporter(new Settings) + val toolbox = new ToolBox(reporter) + val ttree = toolbox.typeCheck(code.tree) + toolbox.runExpr(ttree) +} |