List to list of tuples convertion

混江龙づ霸主 提交于 2019-12-13 15:26:05

问题


I want to convert [z,z,a,z,z,a,a,z] to [{z,2},{a,1},{z,2},{a,2},{z,1}]. How can I do it?

So, I need to accumulate previous value, counter of it and list of tuples.

I've create record

-record(acc, {previous, counter, tuples}).

Redefined

listToTuples([]) -> [];
listToTuples([H | Tail]) -> 
    Acc = #acc{previous=H, counter=1},
    listToTuples([Tail], Acc).

But then I have some trouble

listToTuples([H | Tail], Acc) ->   
    case H == Acc#acc.previous of
        true  ->
        false ->
    end.

回答1:


if you build up your answer (Acc) in reverse, the previous will be the head of that list.

here's how i would do it --

list_pairs(List) -> list_pairs(List, []).

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

(i expect someone will now follow with a one-line list comprehension version..)




回答2:


I would continue on the road building the list in reverse. Notice the pattern matching over X on the first line.

F = fun(X,[{X,N}|Rest]) -> [{X,N+1}|Rest];
       (X,Rest)         -> [{X,1}|Rest] end.

lists:foldr(F,[],List).



回答3:


I would personally use lists:foldr/3 or do it by hand with something like:

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

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

Using two accumulators saves you unnecessarily building and pulling apart a tuple for every element in the list. I find writing it this way clearer.



来源:https://stackoverflow.com/questions/5214821/list-to-list-of-tuples-convertion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!