Search code examples
prologprolog-toplevel

How to write a Prolog rule to define a predicate?


here's the assignment: In a Prolog program, predicates are defined:

  • mother(M,Y)M is the mother of Y
  • father(F,X)F is the father of X

Write Prolog code to implement the predicate:

  • cousins(X,Y)X and Y are cousins
  • brother_or_sister(X,Y)X and Y are brother or sister of each other.

My attempts:

mother(m1, nicolas).
father(f1,nicolas).

mother(m2, mark).
father(f2, mark).

father(f3, f1).
mother(m3, f1).
father(f3, f2).
mother(m3, f2).

brother_or_sister(X, Y) :-
    father(f3, X),
    father(f3, Y),
    mother(m3, X),
    mother(m3, Y).

cousins(X, Y) :-
    (
      mother(m1, X),
      father(f1, X),
      mother(m2, Y),
      father(f2, Y)
    )
    (
      (
        brother_or_sister(m1, m2) ;
        brother_or_sister(f1, f2)
      )
      ;
      (
        brother_or_sister(f1, m2) ;
        brother_or_sister(m1, f2)
      ).

Program output:

true
false

Although it's supposed to be true

Please help!


Solution

  • Brothers and sisters are siblings. Two people are siblings if they have common parentage (and half-siblings if they share just one common parent). So we can say things like:

    parents(F:M,X) :- mother(M,X), father(F,X) . 
    
    sibling(X,Y) :- parents(F:M,X), parents(F:M,Y) .
    

    Similarly, two people are cousins if they have parents who are siblings of each other. That leads to:

    parent(P,X) :- father(P,X) .
    parent(P,X) :- mother(P,X) .
    
    cousin(X,Y) :- parent(Px,X), parent(Py,Y), sibling(Px,Py) .