How to convert List to List of tuples?

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}).


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


  • 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..)