javaprologjpl

How to handle prolog lists in java


I'm using jpl to connect java and prolog. I am trying to handle prolog lists in java. My prolog code when executed returns a list like the following

L = [38, '(60)', '48^10', '36^6^58']

Now i'm trying to handle this output in java using the following code

import jpl.Integer;
import jpl.Query;
import jpl.Variable;
import jpl.JPLException;
import jpl.Term;
import java.awt.List;
import java.lang.Number;
import java.util.Hashtable;
import java.util.Iterator;
public class Family
{   
    int num1;
    public static void  main( String argv[] )
    {       
        String t1 = "consult('Test.pl')";
        Query q1 = new Query(t1);
        System.out.println( t1 + " "
            + (q1.hasSolution() ? "succeeded" : "failed") );
        String t4 = "main(X)";
        Query q4 = new Query(t4);
        System.out.println( "first solution of " + t4 + ": X = "
            +   q4.oneSolution().get("X"));

        Term listTerm = (Term) q4.oneSolution().get("X");
        Term firstListItem = listTerm.arg(1);       
        System.out.println("" + firstListItem);
    }
}

Executing this we get the first solution of the query which is

    X = '.'(38, '.'('(60)', '.'('48^10', '.'('36^6^58', []))))
38

And i'm able to print out the first element of the list which is '38'

In the same i'm unable to handle all the elements of the list. Please help me to do this?


Solution

  • I've never used this API before, but a quick look at the Javadocs for jpl.Term shows that you can call args() to get an array (Term[]) containing all the results.

    You can loop through those:

    ...
    for (Term oneTerm : listTerm.args()) {
      System.out.println(oneTerm);
    }
    

    Note also that the object model allows for n-deep nesting, so if you want to print a full tree of results, you need to recurse, checking each Term's isCompound()...