Search code examples
prolog

Predicate must be true of all elements in a list


I have a set of facts:

likes(john,mary).
likes(mary,robert).
likes(robert,kate).
likes(alan,george).
likes(alan,mary).
likes(george,mary).
likes(harry,mary).
likes(john,alan).

Now I want to write a relation which will check for all element X of an input list if likes(X,A) is true. my relation should return true once if likes(X,A) is true for all element X in my list L. If I try this this:

relat(X) :- member(A,[john,alan,george,harry]), likes(A,X).

but the output is

?- relat(mary).
true ;
true ;
true ;
true.

I want to write it such that it returns one true once it found that likes(john,mary),likes(alan,mary),likes(george,mary),likes(harry,mary) all are true. How to approach this problem?


Solution

  • In SWI-Prolog, you can use forall/2:

    ?- forall(member(A, [john, alan, george, harry]), likes(A, mary)).
    true.
    ?- forall(member(A, [john,alan,george,harry,marys_ex]), likes(A, mary)).
    false.