stpmsth
stpmsth

Reputation: 35

Prolog : how to detirmine if there are duplicate element in a list (not consecutive)

Im wondering how can i write a predicate /1 which determines if a given list has duplicates or is unique without pre-defined/built-in predicates?

myFunc([a,b,c,d]) = true

myFunc([a,b,a,d]) = false

What i have so far is :

myFunc([X|Y]) :- helpFunc(Y,X).
myFunc([]).
helpFunc([],_).
helpFunc([Y|X], Y) :- helpFunc(X,Y).

This returns true only if there are consecutive repeated element in the list.

ex.

myFunc([1,3,a,4,b]) = false -- > should return true

myFunc([1,3,a,3,b]) = false -- > should return false

--

myFunc([3,3,3,3]) = true

any ideas ?

Upvotes: 2

Views: 1337

Answers (1)

user27815
user27815

Reputation: 4797

A simple way to do this is :

duplicate(List):-
 append(X,Y,List),
 member(M,X),
 member(M,Y). 

A list has duplicate elements, if you can split it in to two lists and there is the same member of both these lists.

As prolog does not have functions, a declarative name would be better.

I have used the built in member/2 and append/3 but if you insist you can easily look up the definitions of these.

Upvotes: 3

Related Questions