Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

counting the same elements in the list.

Status
Not open for further replies.

metalazo

Programmer
May 17, 2010
2
IT
Hi everybody, I'm a new user...and I hope that this forum can help me!!!
I've got a list composed by the following elements: (a,b,c,d,e,f,g,h,e)...(the 'e' char is present two times)
ok now I have to verify if the 'e' char belongs to the list. The code is very simple:
member(X,[X|_]).
member(X,[_|Y]):-member(X,Y).
The question to the prolog compiler is :
?-member(e,[a,b,c,d,e,f,g,e]).
In this way I can verify that the 'e' char belongs to the list.
My question is: How can I count the number of 'e' char in the list???

Thanks to all.
Andrea
 
You will have to write a suitable predicate, like member, only for counting occurences of elements within lists:

count(X, List, Occurrences) ...

For example, it will work like this, in your example:

count(e, [a,b,c,d,e,f,g,e], Occurences).
Occurences = 2 ...

The code for it is something like this:

count(_, [], 0).
count(X, [X | T], N) :-
!, count(X, T, N1),
N is N + 1.
count(X, [_ | T], N) :-
count(X, T, N).
 
sorry, there is a mistake in my code ... below is the correct code:

count(_, [], 0).
count(X, [X | T], N) :-
!, count(X, T, N1),
N is N1 + 1.
count(X, [_ | T], N) :-
count(X, T, N).
 
Oh wow, you are great !!!!

thanks a lof, it works fine !!!

bye bye Andrea
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top