blob: 564e7f1cdf0ee626142390b1a94626953db9dace (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
import scala.language.{ implicitConversions }
import scala.reflect.runtime.universe._
import scala.tools.reflect.Eval
object Test extends dotty.runtime.LegacyApp {
reify {
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)
}.eval
}
|