문제

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!

도움이 되었습니까?

해결책

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).

다른 팁

I'd write it like this:

predicate(M1,M2,M3,L):- member(M1,L),member(M1,[M2,M3]).

you say "it says that M1 is either M2 or M3, but not both" but I think that's your responsibility, as a caller of this predicate. If you've supplied equal M2 and M3, evidently you wanted them equal. And if you've supplied them different, well, that's what they are.

Prolog is very different from other programming languages. Your attempt is not unreasonable, but would read better as:

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

This says the same thing, really, but this version draws attention to the fact that we're not doing anything with the fourth argument, which in this formulation could be any single-element list. Odds are good this isn't what you meant.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top