Return 一个值在 Erlang 列表中出现的次数

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

我是 Erlang 的新手。这是我一直在做的练习,但我无法编译我的代码。问题是 return 一个值在列表中出现的次数。

例如:

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

(我不明白"only consider top level of List"的意思。)

这是我的代码:

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

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

我编译的时候说:

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

列表的尾部已经是一个列表,所以当你递归调用你的函数时不需要将它包装在一个新的列表中。改为这样写:

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

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