I'm trying to write a predicate twice(El,L) which will return true. when El is on list exactly twice. Here is what I have:
twice(El,L) :- select(El,L,L1), member(El,L1), \+ twice(El,L1).
It works nice for twice(2,[1,2,2,3,4])
but for twice(X,[1,1,2,2,3,3]) it doubles every number X = 1 ; X = 1 ; X = 2... How could I avoid this without using any accumulator?
You want to describe a sequence of elements. For such, there is a special formalism in Prolog called Definite Clause Grammars. Before using the formalism, let's try to figure out how a sequence with
Eoccurring exactly twice looks like:EEEEE.Now, to put this into the DCG formalism
Or, more compactly by using all//1 and avoiding auxiliary definitions:
There is essentially only one drawback with these definitions: On current systems, they are not optimally implemented. See this if you want to know more.