-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimulation.scala
More file actions
43 lines (33 loc) · 911 Bytes
/
Simulation.scala
File metadata and controls
43 lines (33 loc) · 911 Bytes
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
package week3.event_simulation
abstract class Simulation {
type Action = () => Unit
case class Event(time: Int, action: Action)
private var curTime = 0
private type Agenda = List[Event]
private var agenda: Agenda = List()
def currentTime: Int = curTime
def insert(ag: Agenda, item: Event): Agenda = ag match {
case first :: rest if first.time <= item.time =>
first :: insert(rest, item)
case _ =>
item :: ag
}
private def loop(): Unit = agenda match {
case first :: rest =>
agenda = rest
curTime = first.time
first.action()
loop()
case Nil =>
}
def afterDelay(delay: Int)(block: => Unit): Unit = {
val item = Event(currentTime + delay, () => block)
agenda = insert(agenda, item)
}
def run(): Unit = {
afterDelay(0) {
println("*** simulation started, time = " + currentTime + " ***")
}
loop()
}
}