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 Function implements Term { 018 private String functionName; 019 private List<Term> terms = new ArrayList<Term>(); 020 private String stringRep = null; 021 private int hashCode = 0; 022 023 public Function(String functionName, List<Term> terms) { 024 this.functionName = functionName; 025 this.terms.addAll(terms); 026 } 027 028 public String getFunctionName() { 029 return functionName; 030 } 031 032 public List<Term> getTerms() { 033 return Collections.unmodifiableList(terms); 034 } 035 036 // 037 // START-Term 038 public String getSymbolicName() { 039 return getFunctionName(); 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.visitFunction(this, arg); 052 } 053 054 public Function copy() { 055 List<Term> copyTerms = new ArrayList<Term>(); 056 for (Term t : terms) { 057 copyTerms.add(t.copy()); 058 } 059 return new Function(functionName, copyTerms); 060 } 061 062 // END-Term 063 // 064 065 @Override 066 public boolean equals(Object o) { 067 068 if (this == o) { 069 return true; 070 } 071 if (!(o instanceof Function)) { 072 return false; 073 } 074 075 Function f = (Function) o; 076 077 return f.getFunctionName().equals(getFunctionName()) 078 && f.getTerms().equals(getTerms()); 079 } 080 081 @Override 082 public int hashCode() { 083 if (0 == hashCode) { 084 hashCode = 17; 085 hashCode = 37 * hashCode + functionName.hashCode(); 086 for (Term t : terms) { 087 hashCode = 37 * hashCode + t.hashCode(); 088 } 089 } 090 return hashCode; 091 } 092 093 @Override 094 public String toString() { 095 if (null == stringRep) { 096 StringBuilder sb = new StringBuilder(); 097 sb.append(functionName); 098 sb.append("("); 099 100 boolean first = true; 101 for (Term t : terms) { 102 if (first) { 103 first = false; 104 } else { 105 sb.append(","); 106 } 107 sb.append(t.toString()); 108 } 109 110 sb.append(")"); 111 112 stringRep = sb.toString(); 113 } 114 return stringRep; 115 } 116 }