I 'm trying to find the cardinality of a set in Prolog. As is known, a set can haven't elements repeated. I tried this.
cardinal([], 0).
cardinal([_|Tail], N):-
removeRepeated(Tail, ListWithoutRepeated),
cardinal(ListWithoutRepeated, N1),
N is N1 + 1.
----------------------------------------------------
consult:
?- cardinal([1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5], N).
N = 6
But the correct answer is N = 5. Obviously I'm counting only the items in the tail and ignored if the head is repeated in the tail. So I tried something like this. That is to add the head to tail and repeat the above process.
join([], L, [L]).
join([Head|Tail], L, [Head|Tail2]):-
join(Tail,L, Tail2).
cardinal([], 0).
cardinal([Head|Tail], N):-
join(Tail,Head, List),
removeRepeated(List, ListWithoutRepeated),
cardinal(ListWithoutRepeated, N1),
N is N1 + 1.
But when you query an infinite loop is generated. Can someone help me solve this o can anyone help me out how can I write prolog statement for this?
Edit
attached removeRepeated
removeRepeated([],[]).
removeRepeated([Head|Tail],ListWithoutRepeated):-
member(Head,Tail),
!,
removeRepeated(Tail,ListWithoutRepeated).
removeRepeated([Head|Tail],[Head|ListWithoutRepeated]):-
removeRepeated(Tail,ListWithoutRepeated).
----------------------------------------------------
consult:
?- removeRepeated([1,1,1,1,2,2,2,3,3,3,4,4,4,8], N).
N = [1, 2, 3, 4, 8]