查询Prolog的变量与JPL(Querying Prolog variables with JPL

2019-09-19 12:31发布

我想打一个查询通过JPL在Java中使用Prolog的,我阅读文档(http://www.swi-prolog.org/packages/jpl/java_api/getting_started.html)的序言谓词是这些:

child_of(joe, ralf).
child_of(mary, joe).
child_of(steve, joe).
child_of(steve, ralf).

descendent_of(X, Y) :-
    child_of(X, Y).
descendent_of(X, Y) :-
    child_of(Z, Y),
descendent_of(X, Z).

我的代码看起来是这样的

Variable X = new Variable();

        Query q4 =
            new Query(
                "descendent_of",
                new Term[] {X,new Atom("joe")}
            );

        java.util.Hashtable solution;

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

根据我的序言谓词,我的Java代码应该找回“玛丽”和“史蒂夫”,但我得到这样的:

X = null
X = null

我做错了吗? 提前致谢

编辑 :这是我的整个测试

Query q1 =
    new Query(
        "consult",
        new Term[] {new Atom("C:\\Users\\cardozo\\Documents\\fer\\info2\\lore\\test.pl")}
    );

return q1;

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

Query q2 =
    new Query(
        "child_of",
        new Term[] {new Atom("joe"),new Atom("X")}
    );
Boolean resp= q2.query();
System.out.println("child_of(joe,X) is " + resp.toString()
);

Query q3 =
    new Query(
        "descendent_of",
        new Term[] {new Atom("steve"),new Atom("ralf")}
    );

System.out.println(
    "descendent_of(joe,ralf) is " +
    ( q3.query() ? "provable" : "not provable" )
);

Variable X = new Variable();

Query q4 =
    new Query(
        "descendent_of",
        new Term[] {X,new Atom("joe")}
    );

java.util.Hashtable solution;

q4.query();

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

这是我在我的Java控制台结果得到

run:
% C:\Users\cardozo\Documents\fer\info2\lore\test.pl compiled 0.00 sec, 8 clauses
consult succeeded
child_of(joe,X) is false
descendent_of(joe,ralf) is provable
X = null
X = null
BUILD SUCCESSFUL (total time: 0 seconds)

Answer 1:

我会尝试通过名字来获取变量:

solution.get("X")

编辑

与文字查询像

查询Q4 =新的查询( “descendent_of(X,JOE)”)



Answer 2:

我发现了解决方案,我必须使用类化合物(包括在JPL)这样

Query q4 = new Query(new Compound("descendent_of", new Term[] { new Variable("X"), new Atom("joe")}));

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

而我得到的解决方案

X = mary
X = steve


文章来源: Querying Prolog variables with JPL