Thursday, October 06, 2011

Scala By Example Chapter 11 Solutions - Exercise 11.3.2

Exercise 11.3.2 Another way is to define an or-gate by a combination of inverters and and gates. Define a function orGate in terms of andGate and inverter. What is the delay time of this function?

The delay parameter has also been left unused in this case. However it would not be difficult to conclude that the delay time for this function would be = inverter delay time + AND delay time + inverter delay time = 2 (inverter delay) + AND delay.

object CompoundOrGate {
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 andGate(input1: Wire, input2: Wire, output: Wire) {
def andAction() {
val inputSig1 = input1.getSignal
val inputSig2 = input2.getSignal
afterDelay(0) { output setSignal inputSig1 & inputSig2 }
}
input1 addAction andAction
input2 addAction andAction
}
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 compoundOrGate(input1: Wire, input2: Wire, output: Wire) {
val o1, o2, o3 = new Wire
inverter(input1, o1)
inverter(input2, o2)
andGate(o1, o2, o3)
inverter(o3, output)
}
def main(args: Array[String]) {
val inp1, inp2, output = new Wire
inp1.setSignal(true)
inp2.setSignal(false)
compoundOrGate(inp1, inp2, output)
println("Output of compound OR gate is: " + output.getSignal)
}
}

No comments: