val a = new Wire val b = new Wire val c = new Wire
or, equivalent but shorter, like this:
val a, b, c = new Wire
Second, there are three procedures which “make” the basic gates we need:
def inverter(input: Wire, output: Wire)
def andGate(a1: Wire, a2: Wire, output: Wire) def orGate(o1: Wire, o2: Wire, output: Wire)
What’s unusual, given the functional emphasis of Scala, is that these procedures construct the gates as a side-effect, instead of returning the constructed gates as a result. For instance, an invocation of inverter(a, b) places an inverter between the wires a and b. It turns out that this side-effecting construction makes it easier to construct complicated circuits gradually. Also, although methods most often have verb names, these have noun names that indicate which gate they are making. This reflects the declarative nature of the DSL: it should describe a circuit, not the actions of making one.
More complicated function boxes can be built from the basic gates. For instance, the method shown in Listing 18.6 constructs a half-adder. The halfAdder method takes two inputs, a and b, and produces a sum, s, defined by “s = (a + b) % 2” and a carry, c, defined by “c = (a + b) / 2”. A diagram of the half-adder is shown in Figure 18.2.
def halfAdder(a: Wire, b: Wire, s: Wire, c: Wire) { val d, e = new Wire
orGate(a, b, d) andGate(a, b, c) inverter(c, e) andGate(d, e, s)
}
Listing 18.6 · The halfAdder method.
Note that halfAdder is a parameterized function box just like the three methods that construct the primitive gates. You can use the halfAdder
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index