1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package jTrolog.engine;
23
24 import jTrolog.terms.Struct;
25 import jTrolog.terms.Term;
26 import jTrolog.terms.Clause;
27
28 import java.util.*;
29
30
31
32
33
34
35 @SuppressWarnings({ "rawtypes", "unchecked","serial" })
36 class ClauseDatabase extends LinkedHashMap {
37
38 public void addFirst(Object key, Object d) {
39 LinkedList family = (LinkedList) get(key);
40 if (family == null)
41 put(key, family = new LinkedList());
42 family.addFirst(d);
43 }
44
45 public void addLast(Object key, Object d) {
46 LinkedList family = (LinkedList) get(key);
47 if (family == null)
48 put(key, family = new LinkedList());
49 family.addLast(d);
50 }
51
52 public List getPredicates(Object key) {
53 LinkedList family = (LinkedList) get(key);
54 if (family == null)
55 return new LinkedList();
56 return family;
57 }
58
59 public List getPredicatesIterator(Object key) {
60 return (LinkedList) get(key);
61 }
62
63 public Object restore(Object s) {
64 return s;
65 }
66
67 public LinkedList abolish(Object key) {
68 return (LinkedList) remove(key);
69 }
70
71 public Iterator iterator() {
72 return new CompleteIterator(this);
73 }
74
75 public String toString() {
76 StringBuffer buffer = new StringBuffer();
77 for (Iterator dynamicClauses = iterator(); dynamicClauses.hasNext();) {
78 Struct d = ((Clause) dynamicClauses.next()).original;
79 buffer.append(d.getArg(0).toString());
80 if (d.getArg(1).equals(Term.TRUE))
81 buffer.append(".\n");
82 else
83 buffer.append(":-\n\t").append(d.getArg(1).toString()).append(".\n");
84 }
85 return buffer.toString();
86 }
87
88 private static class CompleteIterator implements Iterator {
89 Iterator values;
90 Iterator workingList;
91 ClauseDatabase cdb;
92
93 public CompleteIterator(ClauseDatabase clauseDatabase) {
94 cdb = clauseDatabase;
95 values = clauseDatabase.values().iterator();
96 }
97
98 public boolean hasNext() {
99 if (workingList != null && workingList.hasNext())
100 return true;
101 if (values.hasNext()) {
102 workingList = ((List) values.next()).iterator();
103 return hasNext();
104 }
105 return false;
106 }
107
108 public Object next() {
109 Clause modified = (Clause) workingList.next();
110 return cdb.restore(modified);
111 }
112
113 public void remove() {
114 workingList.remove();
115 }
116 }
117 }