next up previous contents
Next: Constructing Recursive Data Structures Up: Adding Computation Domains Previous: Structured Data and Data

Structuring Old Problems

Some examples already seen can be rewritten using data structures to increase modularity and to offer more information to the user. We will show an alternative implementation of the program which finds out inputs and outputs of electronic logic gates. The main difference is that we will augment the program to keep track of the structure of the gate also. This structure will be returned to the user so that the basic components of every gate, and not only its connections, are known.

Recalling Figure 2.3, we will add the names of the transistors and resistors to the database:

resistor(r1, power,n1).
resistor(r2, power,n2).
transistor(t2, n3, n4, n2).
transistor(t1, n2, ground, n1).
transistor(t3, n5, ground, n4).

We can now know what are the connections of every component. The rest of the program clauses relate the structure of gates with their inputs and outputs:

inverter(inv(T, R), Input, Output):-
   transistor(T, Input, ground, Output),
   resistor(R, power, Output).

nand_gate(nand(T1, T2, R), Input1, Input2, Output):-
   transistor(T1, Input, X, Output),
   transistor(T2, Input2, ground, X),
   resistor(R, power, Output).

and_gate(and(N, I), Input1, Input2, Output):-
   nand_gate(N, Input1, Input2, X),
   inverter(I, X).

Queries can now return also the components of the gates:

?- and_gate(G, In1, In2, Out).
   G=and(nand(t2, t3, r2), inv(t1, r1)), In1=n3, In2=n5,  Out=n1