aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorShawn O. Pearce <sop@google.com>2011-06-06 08:46:51 -0700
committerShawn O. Pearce <sop@google.com>2011-06-06 09:18:36 -0700
commitcacc2414eb49d66126403e880d9ea7740612ddf6 (patch)
tree29eb96dc5a80c922e0502683c733a2f0e729b168
parent46addafcab94965f1401d97443ee0d95e73ed0b4 (diff)
downloadprolog-cafe-cacc2414eb49d66126403e880d9ea7740612ddf6.tar.gz
Add arity() and arg(int) to Term API
This makes it easier to extract the arguments of a StructureTerm.
-rw-r--r--src/lang/ListTerm.java12
-rw-r--r--src/lang/StructureTerm.java2
-rw-r--r--src/lang/Term.java6
3 files changed, 20 insertions, 0 deletions
diff --git a/src/lang/ListTerm.java b/src/lang/ListTerm.java
index b8d51a2..a585308 100644
--- a/src/lang/ListTerm.java
+++ b/src/lang/ListTerm.java
@@ -111,6 +111,18 @@ public class ListTerm extends Term {
public String name() { return SYM_DOT.name(); }
+ public Term arg(int nth) {
+ Term t = this;
+ int old_nth = nth;
+ while (t.isList() && 0 < nth) {
+ nth--;
+ t = ((ListTerm)t).cdr.dereference();
+ }
+ if (t.isList())
+ return ((ListTerm)t).car;
+ throw new ArrayIndexOutOfBoundsException(old_nth);
+ }
+
/** Returns the length of this <code>ListTerm</code>. */
public int length() {
int count = 0;
diff --git a/src/lang/StructureTerm.java b/src/lang/StructureTerm.java
index e1d8ea8..c2388e5 100644
--- a/src/lang/StructureTerm.java
+++ b/src/lang/StructureTerm.java
@@ -73,6 +73,8 @@ public class StructureTerm extends Term {
*/
public String name(){ return functor.name(); }
+ public Term arg(int nth) { return args[nth]; }
+
public boolean unify(Term t, Trail trail) {
t = t.dereference();
if (t.isVariable()) {
diff --git a/src/lang/Term.java b/src/lang/Term.java
index cfcd732..0c45e00 100644
--- a/src/lang/Term.java
+++ b/src/lang/Term.java
@@ -105,6 +105,12 @@ public abstract class Term implements Serializable,Comparable<Term> {
/** @return the name of this Term, if {@link #isStructure()}. */
public abstract String name();
+ /** @return the arity of this Term, if {@link #isStructure()}. */
+ public int arity() { return 0; }
+
+ /** @return get the nth argument of {@link #isStructure()} or {@link #isList()}. */
+ public Term arg(int nth) { throw new ArrayIndexOutOfBoundsException(nth); }
+
/**
* Check whether this object is convertible with the given Java class type.
* @param type the Java class type to compare with.