1
votes

I have written a program in Prolog and I want to access its results in python. I had tried to write my code using pyDatalog but came across a problem I could not solve. Now I am trying PySwip because it lets me consult the database I had already created.

Below is what my knowledge base looks like.

con('w1',a,c).
con('w2',c,b).
con('w3',b,d).
con('w4',d,a).

up('w1').
up('w3').
down('w2').
down('w4').

check(X,Y):-up(X),atom_concat('+', X, Y).

check(X,Y):-down(X),atom_concat('-', X, Y).

comb(Output,Input,A,B):- con(X,A,B), check(X,Y), append([Y],Input,Output).

comb(Output,Input,A,B):- comb(Out,Input,A,C),con(X,C,B), check(X,Y), append([Y],Out,Output).

If I query comb(O,[],a,b). in SWI-Prolog, the result is O = ['-w2', '+w1']

Now in python I use PySwip to retrieve query results. As a test I ran the code below and got the result a c as expected.

from pyswip import Prolog
prolog = Prolog()
prolog.consult("knowledge_base.pl")
for soln in prolog.query("con('w1',B,C)"):
    print(soln["B"],soln["C"])

However when I ran the code below,

from pyswip import Prolog
prolog = Prolog()
prolog.consult("knowledge_base.pl")
for soln in prolog.query("comb('O',[],a,b)"):
    print(soln["O"])

Nothing happens. Does anyone know why this doesn't work?

1
Are you absolutely sure you need to bring Python and Prolog directly into contact with each other in order to solve your problem? It seems like it might be easier to just do the whole thing in one or the other. - Daniel Lyons
@DanielLyons, I can probably write it all in python, which is something I'm working on. It just so happened that prolog seemed convenient for part of it and I thought it would be interesting if I could combine it with python successfully. - njemal

1 Answers

1
votes

In the pyswip query for O, you've defined it as an atom by enclosing it in single quotes, you need it to be a variable

from pyswip import Prolog
prolog = Prolog()
prolog.consult("knowledge_base.pl")
# Atom 'O': for soln in prolog.query("comb('O',[],a,b)"):
# Should be:
for soln in prolog.query("comb(O,[],a,b)"):
    print(soln["O"])