1

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])

Steve Vinoski
  • 19,847
  • 3
  • 31
  • 46
rapsoulCecil
  • 117
  • 8

1 Answers1

3

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).
Steve Vinoski
  • 19,847
  • 3
  • 31
  • 46