简体   繁体   English

如何在Java中处理Prolog列表

[英]How to handle prolog lists in java

I'm using jpl to connect java and prolog. 我正在使用jpl连接java和prolog。 I am trying to handle prolog lists in java. 我正在尝试使用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 现在我正在尝试使用以下代码在Java中处理此输出

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' 而且我能够打印出列表的第一个元素“ 38”

In the same i'm unable to handle all the elements of the list. 同样,我无法处理列表中的所有元素。 Please help me to do this? 请帮我做这个吗?

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 而不是列表,您可以在数组中使用

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. 我以前从未使用过此API,但是快速jpl.TermJavadocs显示,您可以调用args()来获取包含所有结果的数组( Term[] )。

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() ... 还要注意,对象模型允许n深度嵌套,因此,如果要打印完整的结果树,则需要递归,检查每个Term的isCompound() ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM