Search code examples
prologunification

Unification(?) in Prolog


I have a school project where I have to work with Prolog. This is all new to me, so I'm having some problems.

I have a list like this:

List = [(_,_,_),(_,_,_),(_,_,_)]

I'm supposed to receive from the input information about each member, through several predicates that I must create.

One of them is of the type:

predicate(M1,M2,M3, List)

and it says that M1 is either M2 or M3, but not both. For example,

predicate((_,a,_),(2,_,_),(3,_,_),List)

states that the member with 'a', has either 2 or 3 in the first field.

I've been trying all night but can't come up with a solution. I believe I have to use the unification, but don't know how to do it.

I've tried this:

predicate(M1,M2,M3,[_]) :- (M1=M2), not(M1=M3).
predicate(M1,M2,M3,[_]) :- (M1=M3), not(M1=M2).

This may look ridiculous, but as I said, Prolog is completely new to me and I can't quite grasp its functioning.

Any hint is appreciated. Thanks!

EDIT:

Example:

person(name,age,job).
List = [(einstein,_,_),_,_].

So now I have a list List of 3 people, with einstein in the first position.

predicate = ((einstein,_,_),(_,87,_),(_,23,_), List).

List = [(einstein,87,_),_,_)];
List = [(einstein,23,_),_,_)].

These above are the 2 acceptable lists after applying the predicate.

It should be a simple problem but I can't figure it out.

Thanks!


Solution

  • I guess that you should bind elements in List:

    predicate(M1, M2, M3, [M1, M2, M3]) :-
        M1 = M2, M1 \= M3
      ; M1 = M3, M1 \= M2.
    

    EDIT: after comments

    predicate(M1, M2, M3, List) :-
        member(M1, List),
        ( M1 = M2, M1 \= M3 ; M1 = M3, M1 \= M2 ).
    

    Member/2 it's the most basic relation in Prolog between a list and its elements. Here it shows the ability of the underlying engine to bind variables while searching for a solution.

    Your data yields

    ?- predicate((einstein,_,_),(_,87,_),(_,23,_), [E]).
    E = (einstein, 87, _G3908) ;
    E = (einstein, 23, _G3908).