001 /* 002 * Created on Sep 14, 2003 by Ravi Mohan 003 * 004 */ 005 package aima.logic.fol.parsing.ast; 006 007 import java.util.ArrayList; 008 import java.util.Collections; 009 import java.util.List; 010 011 import aima.logic.fol.parsing.FOLVisitor; 012 013 /** 014 * @author Ravi Mohan 015 * @author Ciaran O'Reilly 016 */ 017 public class Predicate implements AtomicSentence { 018 private String predicateName; 019 private List<Term> terms = new ArrayList<Term>(); 020 private String stringRep = null; 021 private int hashCode = 0; 022 023 public Predicate(String predicateName, List<Term> terms) { 024 this.predicateName = predicateName; 025 this.terms.addAll(terms); 026 } 027 028 public String getPredicateName() { 029 return predicateName; 030 } 031 032 public List<Term> getTerms() { 033 return Collections.unmodifiableList(terms); 034 } 035 036 // 037 // START-AtomicSentence 038 public String getSymbolicName() { 039 return getPredicateName(); 040 } 041 042 public boolean isCompound() { 043 return true; 044 } 045 046 public List<Term> getArgs() { 047 return getTerms(); 048 } 049 050 public Object accept(FOLVisitor v, Object arg) { 051 return v.visitPredicate(this, arg); 052 } 053 054 public Predicate copy() { 055 List<Term> copyTerms = new ArrayList<Term>(); 056 for (Term t : terms) { 057 copyTerms.add(t.copy()); 058 } 059 return new Predicate(predicateName, copyTerms); 060 } 061 062 // END-AtomicSentence 063 // 064 065 @Override 066 public boolean equals(Object o) { 067 068 if (this == o) { 069 return true; 070 } 071 if (!(o instanceof Predicate)) { 072 return false; 073 } 074 Predicate p = (Predicate) o; 075 return p.getPredicateName().equals(getPredicateName()) 076 && p.getTerms().equals(getTerms()); 077 } 078 079 @Override 080 public int hashCode() { 081 if (0 == hashCode) { 082 hashCode = 17; 083 hashCode = 37 * hashCode + predicateName.hashCode(); 084 for (Term t : terms) { 085 hashCode = 37 * hashCode + t.hashCode(); 086 } 087 } 088 return hashCode; 089 } 090 091 @Override 092 public String toString() { 093 if (null == stringRep) { 094 StringBuilder sb = new StringBuilder(); 095 sb.append(predicateName); 096 sb.append("("); 097 098 boolean first = true; 099 for (Term t : terms) { 100 if (first) { 101 first = false; 102 } else { 103 sb.append(","); 104 } 105 sb.append(t.toString()); 106 } 107 108 sb.append(")"); 109 stringRep = sb.toString(); 110 } 111 112 return stringRep; 113 } 114 }