rapsoulCecil
rapsoulCecil

Reputation: 117

Return the number of times a value appears in a list in Erlang

I'm pretty new to Erlang. Here is a practice I've been working on but I cannot compile my code. The problem is to return the number of times a value appears in the list.

e.g.:

count(1, [2, 1, 2, 1, 2, 5])  ----> 2;
count(a, [a, b, c, d]) ----> 1;
count(a, [[a, b], b, {a, b, c}]) ----> 0
%% only consider top level of List

(I don't understand "only consider top level of List" means.)

Here is my code:

-module(project).
-export([count/2]).

count(_, []) -> 0;
count(X, [X|XS]) -> 1 + count(X, [XS]);
count(X, [_|XS]) -> count(X, [XS]).

When I compiled it, it said:

no function clause matching project:count (1,[1,2,1,1,2])

Upvotes: 1

Views: 1249

Answers (1)

Steve Vinoski
Steve Vinoski

Reputation: 20014

The tail of a list is already a list, so you don't need to wrap it in a new list when you call your function recursively. Write it like this instead:

-module(project).
-export([count/2]).

count(_, []) -> 0;
count(X, [X|XS]) -> 1 + count(X, XS);
count(X, [_|XS]) -> count(X, XS).

Upvotes: 3

Related Questions