I want to write a code which will return number of unique elements in the list. My idea is to check if head of the list is there in the list of uniqeue elemeents. If it is not, add it to the list and increment the counter and continue witht the remaining list. So, I tried out following:
count([],0).
count([X,T], N) :-
count([X,T], [], N). %initially list of unique elements is empty
count([X,T], U, N) :- % U is a list of unique elements
(not(member(X, U)), append(U, X, U2));
count(T, U2, N1),
N is N1 + 1.
%------ helpers ------
member_(X,[Y|T]):-
member_(X, T).
member_(X,[X|_]).
append([], Y, [Y]). % append[] and Y to get Y.
append([H|X], Y, [H|Z]) :- append(X, Y, Z). % append [H|X] and Y to get [H|Z] if appending X and Y gives Z
But running above simply return false:
3 ?- count([1,2,3],N).
Call: (10) count([1, 2, 3], _7714) ? creep
Fail: (10) count([1, 2, 3], _7714) ? creep
false.
Why is this so?