Prolog falling into infinite loop

493 Views Asked by At

I'm trying to define the rule of "My friend's friend is my friend" in prolog, and I have the following code:

friends(john,jake).
friends(mike,hans).
friends(hans,robert).
friends(robert,angela).

mutual_friendship(X,Y):-
    friends(X,Y); 
    friends(Y,X).

friendship(X,Y):- 
    mutual_friendship(X,Y),!;
    mutual_friendship(Y,Z), friendship(Z,X).

And it does that pretty well, it is capable to detect friendship between Mike and Angela through Hans and Robert, the problem is when I try to find friendship between John and Angela, for example, who are not linked, but the program falls into an infinite loop.

1

There are 1 best solutions below

4
On

mutual_friendship/2 is not slightly related here, I suppose.

friendship(X,Y):-
    ( friends(X,Y)
    ; friends(X,Z), friendship(Z,Y)
    ).

And for given facts

friends(john,jake).
friends(mike,hans).
friends(hans,robert).
friends(robert,angela).

we could get

?- friendship(john,angela).
false.

?- friendship(mike,angela).
true .