Querying Prolog variables with JPL

感情迁移 提交于 2019-12-23 19:49:35

问题


I want to make a query to use Prolog in java through JPL, I read the documentation (http://www.swi-prolog.org/packages/jpl/java_api/getting_started.html) The prolog predicates are these:

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

My code looks like this

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));
        }

According to my prolog predicates, my java code should retrieve 'mary' and 'steve', but I get this:

X = null
X = null

What I'm doing wrong? thanks in advance

EDIT: this is my entire testing

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"));
}

And this is what I get in my java console as result

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)

回答1:


I would try to get variable by name:

solution.get("X")

edit

with a literal query like

Query q4 = new Query("descendent_of(X,joe)")




回答2:


I found the solution, I have to use the class Compound (included in jpl) like this

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"));
        }

And I get the solution

X = mary
X = steve


来源:https://stackoverflow.com/questions/11494747/querying-prolog-variables-with-jpl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!