在JPL中查询多个结果的Prolog

时间:2014-10-03 14:22:42

标签: java netbeans prolog stack-overflow jpl

我想在Prolog中为AI建立一个知识库。首先,我想通过与大象,巨型蚂蚁等做一个玩具示例来尝试学习Prolog及其用途。

我正在使用:NetBeans 8.0.1,SWI-Prolog 6.6.6和Windows 8.1。一切都是64位,并正确设置环境变量。我还链接到NetBeans库中的jpl.jar

我的Prolog知识库如下所示:

bigger(elephant, horse).
bigger(horse, donkey).
bigger(donkey, dog).
bigger(donkey, monkey).
bigger(monkey, ant).
bigger(monkey, dog).
bigger(giant_ant, elephant).

is_bigger(X, Y) :- bigger(X, Y).
is_bigger(X, Y) :- bigger(X, Z), is_bigger(Z, Y).

this的启发。 知识库在SWI-Prolog中没有任何错误。

但是,当Java在Java中大于ant时尝试获取多个答案时,我遇到了堆栈溢出错误。

这是我使用JPL的Java代码的片段。

Query q1 =
    new Query(
        "consult",
        new Term[] {new Atom("pathToFile\\bigger.pl")}
    );

System.out.println( "consult " + (q1.query() ? "succeeded" : "failed"));

Query q2 =
    new Query(
        "bigger",
        new Term[] {new Atom("giant_ant"),new Atom("elephant")}
    );
Boolean resp= q2.query();
System.out.println("bigger(elephant, horse) is " + resp.toString());

Query q3 =
    new Query(
        "is_bigger",
        new Term[] {new Atom("giant_ant"),new Atom("ant")}
    );

System.out.println(
    "is_bigger(giant_ant, ant) is " +
    ( q3.query() ? "provable" : "not provable" )
);

Query q4 = new Query("is_bigger(X, ant)");

java.util.Hashtable solution;

q4.query();

while ( q4.hasMoreSolutions() ){
    solution = q4.nextSolution();
    System.out.println( "X = " + solution.get("X"));
}

Java代码主要取自here

从NetBeans中的调试器中可以看出,当Java试图在代码片段末尾确定solution.get("X")的值时,似乎会发生堆栈溢出错误。

这是我的控制台输出:

consult succeeded
bigger(elephant, horse) is true
is_bigger(giant_ant, ant) is provable
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at jpl.Term.getTerm(Term.java:614)
at jpl.Term.getTerm(Term.java:652)
at jpl.Term.getTerm(Term.java:652)
at jpl.Term.getTerm(Term.java:652)
at jpl.Term.getTerm(Term.java:652)
at jpl.Query.get1(Query.java:334) (and many more like this.)

关于如何解决这个问题的任何想法?如果需要,我很乐意提供更多信息。

1 个答案:

答案 0 :(得分:0)

我无法让它在我的机器上运行JPL,但是从查看文档中你可能想要使用Variable对象并构建查询,就像你为q3所做的那样:

Variable X = new Variable("X");
Query   q4 = new Query("is_bigger", new Term[]{X, new Atom("ant")});

while ( q4.hasMoreElements() ) {
 java.util.Hashtable solution = (Hashtable) q4.nextElement();
 System.out.println( "X = " + (Term) solution.get("X"));
}