prologprolog-dif

One common hobby between two persons in Prolog


I found this old question ( Prolog Predicate to return true when two people have same hobby ) for writing some code to find the same hobby between two persons using dif. I have a similar situation, to display the names of two persons that have the same hobbies,but the hobbies element is defined as a list. Whatever I try it doesn't seem to work, any ideas would be appreciated.

This is what I have so far:

one_common_hobby(P1,P2):-
   dif(P1,P2),
   person(P1,_,_,hobbies([H|Tail])),
   person(P2,_,_,hobbies([H|Tail])),
   member(P1,Tail),
   member(P2,Tail).

Solution

  • For simplicity, suppose the predicate person is defined as follows:

    person(ann, hobbies([fishing, pottery, chess])).
    person(bob, hobbies([parkour, painting, origami])).
    person(coy, hobbies([hunting, fishing, parkour, chess])).
    

    To find two different persons (P1 and P2) who have a common hobby you must:

    have_common_hobby(P1, P2) :-
        dif(P1, P2),
        person(P1, hobbies(H1)),
        person(P2, hobbies(H2)),
        once( ( member(X, H1),
                member(X, H2) ) ).
    

    Example:

    ?- have_common_hobby(A, B).
    A = ann,
    B = coy ;
    A = bob,
    B = coy ;
    A = coy,
    B = ann ;
    A = coy,
    B = bob ;
    false.