How to express the allDifferent/6 predicate?

284 Views Asked by At

Let allDifferent(A, B, C, D, E, F) be true if and only if ∀i, j in {1, 2, 3, 4, 5, 6}, the i-th and j-th arguments unify if and only if i = j.

Thus allDifferent(3, 1, 4, 1, 5, 9) is false, but allDifferent(3, 1, 4, 2, 5, 9) is true.

How does one implement allDifferent/6 in Prolog?

In particular, is there a way to express it that does not require listing the 6-choose-2 = 15 non-equalities AB, AC, ..., EF (or, rather, their Prolog rendition)?

1

There are 1 best solutions below

3
max66 On BEST ANSWER

If you accept that allDifferent receive a list of values (instead of six values) I can propose the following solution

isDifferent(_, []).

isDifferent(X, [H | T]) :-
  X \= H,
  isDifferent(X, T).

allDifferent([]).

allDifferent([H | T]) :-
  isDifferent(H, T),
  allDifferent(T).

-- EDIT --

As suggested by False, you can use dif/2 instead of \= (if your Prolog provide it) so the main isDifferent/2 can be

isDifferent(X, [H | T]) :-
  dif(X, H),
  isDifferent(X, T).

Anyway... hoping this is obvious... but if you really want a allDifferent/6 instead a allDifferent/1 that receive a list, you can define your allDifferent/6 as follows

allDifferent(A, B, C, D, E, F) :-
  allDifferent([A, B, C, D, E, F]).