blob: 8496ae28583e9bc51d66fe484631f456f7445f99 (
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
62
63
64
65
66
67
68
69
70
71
72
73
|
import scala.collection.mutable.HashMap
import scala.util.continuations._
object Test extends Application {
class Store[K,V] {
trait Waiting {
def key: K
def inform(value: V): Unit
}
private val map = new HashMap[K, V]
private var waiting: List[Waiting] = Nil
def waitFor(k: K, f: (V => Unit)) {
map.get(k) match {
case Some(v) => f(v)
case None => {
val w = new Waiting {
def key = k
def inform(v: V) = f(v)
}
waiting = w :: waiting
}
}
}
def add(key: K, value: V) {
map(key) = value
val p = waiting.partition(_.key == key)
waiting = p._2
p._1.foreach(_.inform(value))
}
def required(key: K) = {
shift {
c: (V => Unit) => {
waitFor(key, c)
}
}
}
def option(key: Option[K]) = {
shift {
c: (Option[V] => Unit) => {
key match {
case Some(key) => waitFor(key, (v: V) => c(Some(v)))
case None => c(None)
}
}
}
}
}
val store = new Store[String, Int]
def test(p: Option[String]): Unit = {
reset {
// uncommenting the following two lines makes the compiler happy!
// val o = store.option(p)
// println(o)
val i = store.option(p).getOrElse(1)
println(i)
}
}
test(Some("a"))
}
|