001    /*
002     * Created on Dec 4, 2004
003     *  
004     */
005    package aima.logic.propositional.visitors;
006    
007    import java.util.HashSet;
008    import java.util.Set;
009    
010    import aima.logic.propositional.parsing.ast.BinarySentence;
011    import aima.logic.propositional.parsing.ast.Sentence;
012    import aima.logic.propositional.parsing.ast.Symbol;
013    import aima.logic.propositional.parsing.ast.UnarySentence;
014    
015    /**
016     * @author Ravi Mohan
017     * 
018     */
019    
020    public class CNFClauseGatherer extends BasicTraverser {
021            AndDetector detector;
022    
023            public CNFClauseGatherer() {
024                    detector = new AndDetector();
025            }
026    
027            @Override
028            public Object visitBinarySentence(BinarySentence bs, Object args) {
029    
030                    Set<Sentence> soFar = (Set<Sentence>) args;
031    
032                    Sentence first = bs.getFirst();
033                    Sentence second = bs.getSecond();
034                    processSubTerm(second, processSubTerm(first, soFar));
035    
036                    return soFar;
037    
038            }
039    
040            private Set<Sentence> processSubTerm(Sentence s, Set<Sentence> soFar) {
041                    if (detector.containsEmbeddedAnd(s)) {
042                            return (Set<Sentence>) s.accept(this, soFar);
043                    } else {
044                            soFar.add(s);
045                            return soFar;
046                    }
047            }
048    
049            public Set<Sentence> getClausesFrom(Sentence sentence) {
050                    Set<Sentence> set = new HashSet<Sentence>();
051                    if (sentence instanceof Symbol) {
052                            set.add(sentence);
053                    } else if (sentence instanceof UnarySentence) {
054                            set.add(sentence);
055                    } else {
056                            set = (Set<Sentence>) sentence.accept(this, set);
057                    }
058                    return set;
059            }
060    
061    }