如何计算列表中每个字符的出现次数?

时间:2016-12-19 17:34:53

标签: erlang

如何计算列表中所有连续重复的元素,并将它们与它们出现的次数一起打包。

示例:

compress("Hello") == [{1,$H},{1,$e},{2,$l},{1,$o}]

我试过这个功能,但我有错误,有人可以帮我解决:

compress([])->
    [];
compress(L)->
    helper(L,0).

helper([], _)->
    [];
helper([H|T], Count)->
    case H == hd(T) of
        true -> helper(T,Count), [{Count+1, H}];
        false -> helper(T, Count), [{Count, H}]
    end.

1 个答案:

答案 0 :(得分:1)

这样:

compress(L) ->
    helper(L, []).

helper([], Acc) -> lists:reverse(Acc);
helper([H|T], [{Count, H}|Acc]) ->
    helper(T, [{Count+1, H}|Acc]);
helper([H|T], Acc) ->
    helper(T, [{1, H}|Acc]).

或者更直接,在某些平台上更快(更少垃圾生成)版本:

compress2([]) -> [];
compress2([H|T]) ->
    helper2(T, H, 1).

helper2([H|T], H, Count) ->
    helper2(T, H, Count+1);
helper2([H|T], C, Count) ->
    [{Count, C}|helper2(T, H, 1)];
helper2([], C, Count) ->
    [{Count, C}].