1
votes

I need to do a function in Prolog that, given a list, check if every member is different. The only particularity is that it must not count "_" variables. Here is an example of what I want :

unique([3,1,2]). 
> true

unique([3,1,2,_]).
> true

unique([3,1,2,_,_,_]).
> true

unique([3,1,2,1]).
> false

unique([3,1,2,1,_]).
> false

I already tried with the following function, using the predicate "var" to check if the variable is free or not, but it doesn't work :

element(X,[X|_]) :- !.
element(X,[_|Q]) :- element(X,Q).

unique([]).
unique([_,[]]).
unique([T,Q]) :- var(T), unique(Q), !.
unique([T|Q]) :- \+element(T,Q),unique(Q).

Thank you for your help

PS: I'm using GProlog

PS2: I know that the function fd_all_different could work, but I'd rather implement it myself

1
What should unique([3,1,2,X,X]). do?Arndt Jonasson
Basically, I do not have this case in my program, so it doesn't matterbastien-r
+1 for using this nice name in place of all_different/1. See this.false
And this should your Prolog not have dif/2 definedfalse
A couple of typographical issues: unique([_,[]]). ==> unique([_]). and unique([T,Q]) :- ... ==> unique([T|Q]) :- ....lurker

1 Answers

2
votes

Problem solved thanks to @false:

For those who wonder how, here's the "unique" function :

dif(X,Y) :- X \== Y.

unique([]).
unique([T|Q]) :- maplist(dif(T), Q), unique(Q).