Prolog Infinite Loop: Bi-Directional Predicates

Viewed 90

I'm using https://swish.swi-prolog.org/ as an online Prolog sandbox, but with the simple code below, where I'm trying to define a bidirectional statement to check if 2 atoms(I think?) share a friend, the program seems to be stuck in an infinite loop. What have I done wrong?

friends(lisa, jack).
friends(lisa, jane).

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

mutual_friends(X, Y) :- friends(X, Z), friends(Y, Z).

When I query mututal_friends(jack, jane) I get an infinite loop.

1 Answers

The thing is that your rule can expand infinitely. You should define a friend_ predicate to define friendships and then friend(X, Y) :- friend_(X, Y) ; friend_(Y, X).

Related