Thursday, October 06, 2011

Scala By Example Chapter 11 Solutions - Exercise 11.3.1

Exercise 11.3.1 Write the implementation of orGate.

Note that the delay parameter in the function afterDelay has not been used since it removes complexity when testing this case.

object SimpleOrGate {
type Action = () => Unit
class Wire {
private var sigVal = false
private var actions: List[Action] = List()
def getSignal = sigVal
def setSignal(s: Boolean) =
if (s != sigVal) {
sigVal = s
actions.foreach(action => action())
}
def addAction(a: Action) {
actions = a :: actions; a()
}
}
//The delay parameter is not used.
def afterDelay(delay: Int)(block: => Unit) = block
def inverter(input: Wire, output: Wire) {
def invertAction() {
val inputSig = input.getSignal
afterDelay(0) { output setSignal !inputSig }
}
input addAction invertAction
}
def orGate(input1: Wire, input2: Wire, output: Wire) {
def orAction() {
val inputSig1 = input1.getSignal
val inputSig2 = input2.getSignal
afterDelay(0) { output setSignal inputSig1 | inputSig2 }
}
input1 addAction orAction
input2 addAction orAction
}
def main(args: Array[String]) {
val inp1, inp2, output = new Wire
inp1.setSignal(true)
inp2.setSignal(false)
orGate(inp1, inp2, output)
println("Output of simple OR gate is: " + output.getSignal)
}
}

No comments: