0

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?

ObscureRobot
  • 7,306
  • 2
  • 27
  • 36
Anil
  • 2,405
  • 6
  • 25
  • 28

2 Answers2

0

You can define a method like this

private static String lista(Term listTerm) {
    String lista="";

    while(listTerm.arity() == 2){
        lista = lista + listTerm.arg(1);
        listTerm = listTerm.arg(2);
     }
    return lista;
}

and instead of a list, you can use in array

Mario L
  • 224
  • 1
  • 11
0

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()...

Dilum Ranatunga
  • 13,254
  • 3
  • 41
  • 52
  • I've tried using Term[], but how to display all args. Using your for loop i'm able to display only first argument. – Anil Oct 20 '11 at 23:16