1
votes

I tried to use the library gnu prolog for java to execute a prolog file. I managed to make it work for a basic predicate, but when I try to parse lists the output of prolog engine, it does not work correctly.

My java code is as follows:

    gnu.prolog.vm.Environment environment = new Environment();
environment.ensureLoaded(AtomTerm.get(PrologTest.class.getResource("main.pro").getFile()));

    gnu.prolog.vm.Interpreter interp = environment.createInterpreter();
    environment.runInitialization(interp);

    Term[] listElements = { new IntegerTerm(1), new IntegerTerm(2)};
    Term termElements = new CompoundTerm(TermConstants.listTag, listElements);
    Term[] listElements2 =  { new IntegerTerm(1), new IntegerTerm(2)};
    Term termElements2 = new CompoundTerm(TermConstants.listTag, listElements2);
    Term[]argumentsQuestion = {termElements,termElements2};

    CompoundTerm goalTerm = new CompoundTerm(AtomTerm.get("same"), argumentsQuestion);

    int rc;
    Interpreter.Goal goal = interp.prepareGoal(goalTerm);
     rc = interp.execute(goal); 
     System.out.println("rc value"+rc); 
        if (rc == PrologCode.SUCCESS || rc == PrologCode.SUCCESS_LAST)
        { System.out.println("OK"); }else{
      System.out.println("error"); }

My file main.pro contains the following predicate:

same([H1|R1], [H2|R2]):- H1 is H2 , same (R1,R2).
same([], []) :- true.

The problem is the value of rc is always -1. I tried to modify the file main.pro as follows:

same([H1|R1], [H2|R2]):- H1 is H2.
same([], []) :- true.

The program works correctly in this case, so the program parses correctly the list and reads correctly the first value of the list.

1

1 Answers

0
votes

The standard is/2 predicate performs arithmetic evaluation by evaluating the second argument as an arithmetic expression and unifying the result with the first argument.

Try instead:

same([H| R1], [H| R2]):- same(R1,R2).
same([], []).

But note this accomplishes the same as the following much simpler definition:

same(List, List).

or:

List1 = List2

Maybe you want/need to use term equality instead of term unification as in the solutions above? If that's the case, try:

same([H1| R1], [H1| R2]):- H1 == H2, same(R1,R2).
same([], []).