2

I'm struggling with a homework. A need to find a connection between entities in a knowledge base like this:

find a relation between o1 and o3, for example.

rel(o1,p1,s2).
rel(o2,p2,s4).
rel(o3,p2,s1).
rel(o7,p5,s5).
rel(o9,p1,s4).
rel(o2,p6,s7).
rel(o3,p3,s2).
rel(o6,p6,s3).
rel(o5,p7,s2).
rel(o4,p2,s1).
rel(o3,p3,s1).

where p is a relation.

What I've done so far is:

go(X,Y):-write(X),write(":1e: "),rel(X,Z,_),write(Z),write(":1r: "),
         rel(Y,Z,_),write(Y),write(":1e: "),!.

go(X,Y):-write(X),write(":2e: "),rel(X,Z,V),write(Z),write(":2r: "),
         write(V),write(":2v: "),rel(Y,W,V),write(W),write(":2r: "),
         write(Y),write(":2e: "),!.

go(X,Y):-write(X),write(":3e: "),rel(X,Z,_),write(Z),write(":3r: "),
         rel(W,Z,_),write(W),write(":3e: "),go(W,Y),!.

go(X,Y):-write(X),write(":4e: "),rel(X,_,V),write(V),write(":4v: "),
         rel(W,_,V),write(W),write(":4e: "),go(W,Y).

But when I try to find the connection between o1 and o3

go(o1, o3)

The program get stuck in the first recursive iteration.

lurker
  • 56,987
  • 9
  • 69
  • 103
Max Fratane
  • 747
  • 1
  • 7
  • 21
  • 2
    this question may help: https://stackoverflow.com/questions/44557272/stop-condition-for-recursion-in-prolog – coder Jun 16 '17 at 00:28

1 Answers1

3

I was not looking at your code, because sometimes happens to stuck in some blind point.

I've just make 2 formulas to define this problem, first one is checking if exists direct relation, so that this finder could end.

Another one is looking for relation for the first argument,and some other point. This program have one weak point (but I couldn't see if it affects in your example) - cycles. If you had cycles in your relations than you've got to use list to cache points that you've already been in.

relFinder(X1,X2) :- 
    (rel(X1,P,X2) ; rel(X2,P,X1)), 
    write(X1),write(" "),
    write(P) ,write(" "),
    write(X2).

relFinder(X1,X2) :- 
(rel(X1,P,XT) ; rel(XT,P,X1)),
    write(X1),write(" "),
    write(P) ,write(" "),
    relFinder(XT,X2).
Armatorix
  • 1,083
  • 10
  • 23