maoyi
maoyi

Reputation: 453

How to read each element within a tuple from a list

I want to write a program which will read in a list of tuples, and in the tuple it will contain two elements. The first element can be an Object, and the second element will be the quantity of that Object. Just like: Mylist([{Object1,Numbers},{Object2, Numbers}]).
Then I want to read in the Numbers and print the related Object Numbers times and then store them in a list.
So if Mylist([{lol, 3},{lmao, 2}]), then I should get [lol, lol, lol, lmao, lmao] as the final result.
My thought is to first unzip those tuples (imagine if there are more than 2) into two tuples which the first one contains the Objects while the second one contains the quantity numbers.
After that read the numbers in second tuples and then print the related Object in first tuple with the exact times. But I don't know how to do this. THanks for any help!

Upvotes: 1

Views: 410

Answers (1)

Steve Vinoski
Steve Vinoski

Reputation: 20024

A list comprehension can do that:

lists:flatten([lists:duplicate(N,A) || {A, N} <- L]).

If you really want printing too, use recursion:

p([]) -> [];
p([{A,N}|T]) ->
    FmtString = string:join(lists:duplicate(N,"~p"), " ")++"\n",
    D = lists:duplicate(N,A),
    io:format(FmtString, D),
    D++p(T).

This code creates a format string for io:format/2 using lists:duplicate/2 to replicate the "~p" format specifier N times, joins them with a space with string:join/2, and adds a newline. It then uses lists:duplicate/2 again to get a list of N copies of A, prints those N items using the format string, and then combines the list with the result of a recursive call to create the function result.

Upvotes: 3

Related Questions