Please help with this Prolog question

I’m using:

SWI-Prolog version 8.4.3

I want the code to:

Write a hasDuplicates(List) rule that returns true if a list has duplicate items
% (you don’t need explicit recursion, actually).

But what I’m getting is:

getting an error

My code looks like this:

hasDuplicates(List):-
   queHas_Duplicate(List,X,0).

queHas_Duplicate(_,X,2):-
   write(X).

queHas_Duplicate([Y|T],Y,Count):- 
   queHas_Duplicate(T,Y,NextCount).

First off, it’s not “returns true” but “succeeds”.
Secondly, you’re writing a message if there’s a duplicate; you should just succeed (at least, I assume that’s what your instructor wants).
Third, the first clause of queHas_Duplicate/2 is intended (I presume) to check for the count equalling 2; but all it’s doing is setting the count to 2.

Some hints:

  • When you consulted this program, you probably got warnings about “singleton variables”. Those warnings should usually be taken seriously.
  • A duplicate exists if the count is 2 or greater (not just equal to 2).
  • How would you describe the action of checking for a duplicate in English (or whatever your native language is)? Try to write down a formal definition, and then see if you can write a predicate that matches that

PS: Where I come from, it’s good manners to say “please” when asking for help.

2 Likes

Just to be fair to the OP. As they are new here they actually partially posted a question then posted the same question in full. I suspect they accidently committed the change, then not knowing how to edit the mistake started again. I did delete the partial question as it was obviously a partial of the following post. In that I do recall them using Please in the title, so I will fix it for them. :slightly_smiling_face: