Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 import java.util.Map;

Customised version of Belief Base where some beliefs are unique (with primary keys) and indexed for faster access.

E.g. in a .mas2j project file:
agents: bob beliefBaseClass"student(key,_)", "depot(_,_,_)")
The belief "student/2" has the first argument as its key, so the BB will never has two students with the same key. Or, two students in the BB will have two different keys. The belief "depot/3" has no key, so there will be always only one "depot" in the BB. When some belief with the same key than another belief in BB is added, the most recent remains in the BB and the older is removed.

 public class IndexedBB extends ChainBBAdapter {
     Unifier               u = new Unifier();
     public IndexedBB() {  }
     public IndexedBB(BeliefBase next) {
     public void init(Agent agString[] args) {
         for (int i=0; i<args.lengthi++) {
             Structure bel = Structure.parse(args[i]);
             .put(bel.getFunctor(), bel);
     // TODO: access indexes 
     public boolean add(Literal bel) {
         Structure kb = .get(bel.getFunctor());
         if (kb != null && kb.getArity() == bel.getArity()) { // is a constrained bel?
             // find the bel in BB and eventually remove it
             Literal linbb = null;
             boolean remove = false;
             Iterator<Literalrelevant = getCandidateBeliefs(belnull);
             if (relevant != null) {
                 final int kbArity = kb.getArity();
                 while (relevant.hasNext() && !remove) {
                     linbb =;
                     if (!linbb.isRule()) {
                         // check equality of all terms that are "key"
                         // if some key is different, no problem
                         // otherwise, remove the current bel
                         boolean equals = true;
                         for (int i = 0; i<kbArityi++) {
                             Term kbt = kb.getTerm(i);
                             if (!kbt.isVar()) { // is key?
                                 if (!.unifies(bel.getTerm(i), linbb.getTerm(i))) {
                                     equals = false;
                         if (equals) {
                             remove = true;
             if (remove) {
         return super.add(bel);
     public BeliefBase clone() {
         IndexedBB nbb = new IndexedBB(.clone());
         nbb.indexedBels = new HashMap<String,Structure>(this.);
         return nbb;
New to GrepCode? Check out our FAQ X