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

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.

Upvotes: 3

Views: 1436

Answers (3)

rvirding
rvirding

Reputation: 20916

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.

Upvotes: 3

Magnus Kronqvist
Magnus Kronqvist

Reputation: 1589

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

Upvotes: 6

butter71
butter71

Reputation: 2723

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

Upvotes: 9

Related Questions