Search code examples
prologinfinite-loop

Prolog repeating the same answer infinitely


These are my facts:

married(man, widow).
married(father,daughter).
married(widow, man).
married(daughter,father).

parent(father, man).
parent(widow, daughter).
parent(man, bboy).

% here is the rule giving me problems,

parent(X,Y):-
   married(Z,X),
   parent(Z,Y).

when I run parent(X,Y) it returns the same answers infinitely as such

  ?- parent(X,Y).

X = father
Y = man ? ;

X = widow
Y = daughter ? ;

X = man
Y = bboy ? ;

X = widow
Y = bboy ? ;

X = widow
Y = daughter ? ;

X = widow
Y = bboy ? ;

X = widow
Y = daughter ? ;

How do I stop it from repeating, because when another rule calls the parent rule it crashes prolog


Solution

  • Your problem is here:

    parent(X,Y):-
        married(Z,X),
        parent(Z,Y).
    

    Actually, you can see it a little more clearly if you remove married/2:

    parent(X,Y):-
        parent(Z,Y).
    

    This is going to lead to unbounded recursion. The simple thing to do is rename either the rule or the facts:

    parent(father, man).
    parent(widow, daughter).
    parent(man, bboy).
    
    parent_of(X, Y) :-
        married(Z, X),
        parent(Z, Y).
    

    No more recursion.