ExecutionStyle21
ExecutionStyle21

Reputation: 47

How to count occurence of an item in a list?

I have been messing around with Haskell for two weeks now and have some functions written in Haskell. I heard that Erlang was quite similar(since they are both predominately functional) so I thought I would translate some of these functions to see if I could get them working in Erlang. However I have been having trouble with the syntax for this function I wrote. The purpose of this function is to simply take a character or int and go through a list. After it goes through the list I am just trying to count the amount of times that item occurs. Here is an example run it should return the following.

 count (3, [3, 3, 2, 3, 2, 5])  ----> 3
 count (c, [ a, b, c, d]) ----> 1

Whenever I run my code it just keeps spitting out syntax issues and it is really a pain debugging in Erlang. Here is the code I have written:

count(X,L) ->
  X (L:ls) ->
  X == L = 1+(count X ls);
  count X ls.

Any ideas I can do to fix this?

Upvotes: 2

Views: 3123

Answers (2)

brucify
brucify

Reputation: 331

Use list comprehension in Erlang:

Elem = 3,
L = [3, 3, 2, 3, 2, 5],

length([X || X <- L, X =:= Elem]) %% returns 3

Upvotes: 3

mipadi
mipadi

Reputation: 410602

It's not clear what you're going for, as your syntax is pretty far off. However, you could accomplish your call with something like this:

count(Needle, Haystack) -> count(Needle, Haystack, 0).

count(_, [], Count) -> Count;
count(X, [X|Rest], Count) -> count(X, Rest, Count+1);
count(X, [_|Rest], Count) -> count(X, Rest, Count).

To elaborate, you're creating a recursive function called count to find instances of Needle in Haystack. With each call, there are 3 cases to consider: the base case, where you have searched the entire list; the case in which the value you're searching for matches the first item in the list; and the case in which the value you're searching for does not match the first item in the list. Each case is a separate function definition:

count(_, [], Count) -> Count;

Matches the case in which the Haystack (i.e., the list you are scanning) is empty. This means you do not have to search anymore, and can return the number of times you found the value you're searching for in the list.

count(X, [X|Rest], Count) -> count(X, Rest, Count+1);

Matches the case in which the value you're searching for, X, matches the first item in the list. You want to keep searching the list for more matches, but you increment the counter before calling count again.

count(X, [_|Rest], Count) -> count(X, Rest, Count).

Matches the case in which the value you're searching for does not match the head of the list. In this case, you keep scanning the rest of the list, but you don't increment the counter.

Finally,

count(Needle, Haystack) -> count(Needle, Haystack, 0).

Is a helper that calls the three-argument version of the function with an initial count of 0.

Upvotes: 8

Related Questions