Question

Hi I am new to prolog and I want to know how to express "not all the same" logically in prolog.

for example, if I have a function valid(A, B, C, D) that takes numbers as input and requires A B C D are not all the same, how do I state it?

I tried valid(A, B, C, D) :- not(A == B == C == D). It seems not working.

Was it helpful?

Solution

==/2 is a binary predicate, '=='(X,Y), that will succeed or fail depending upon whether X and Y are bound to the same value. So you can't "cascade" them like A == B == C as it would be a syntax error.

What you can do is individual pairs. This would be an adequate test to tell if any one of A, B, C or D are different (i.e., they are "not all the same"):

valid(A, B, C, D) :-
    \+ (A == B, A == C, A == D).

You could generalize this to a list of numbers, [A,B,C,...]:

valid([X|T]) :- \+ maplist(==(X), T).

And get:

| ?- valid([a,a,a,a]).

no
| ?- valid([a,a,a,b]).

yes

OTHER TIPS

Update:

Check out the question "different/2 - does a pure, determinate definition exist?":

Multiple answers (like this one) manage to combine efficiency and , which makes the code I wrote in this answer obsolete. The old code is still available at the end of this answer... but better ways have been found!


Use the builtin predicate dif/2 for safely expressing term inequality! For details, see .

With dif/2 and member/2 you could implement valid/4 like this:

valid(A,B,C,D) :- 
   dif(X,Y),
   member(X,[A,B,C,D]),
   member(Y,[A,B,C,D]).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top