erlang - How to use lists:duplicate? -
i know if possible use lists:duplicate in case:
decompress_1([])-> []; decompress_1(l)-> mynum = lists:map(fun(t)-> element(1,t) end,l), res = lists:map(fun(t)-> element(2,t) end,l).
to :
decompress_1([{3,1},{3,2},{1,5},{1,4},{1,1},{1,0},{1,1}]) == [1,1,1,2,2,2,5,4,1,0,1]
i manage retrieve first , second elements of tuple. there solution list comprehension know without.
decompress([]) -> []; decompress(l) -> [y || {x, y} <- l, _ <- lists:seq(1, x)].
without using list comprehension, can use lists:duplicate/2
create result, have flatten desired final answer:
decompress([]) -> []; decompress(l) -> lists:flatten(lists:map(fun({x,y}) -> lists:duplicate(x,y) end, l)).
without flatten
we'd first result shown below, instead of second correct result:
1> decompress_no_flatten([{3,1},{3,2},{1,5},{1,4},{1,1},{1,0},{1,1}]). [[1,1,1],[2,2,2],[5],[4],[1],[0],[1]] 2> decompress([{3,1},{3,2},{1,5},{1,4},{1,1},{1,0},{1,1}]). [1,1,1,2,2,2,5,4,1,0,1]
by way, can use lists:duplicate/2
in original list comprehension approach well:
decompress([]) -> []; decompress(l) -> [y || {x,y} <- l, _ <- lists:duplicate(x,y)].
this works because here don't use values produced lists:seq/2
or lists:duplicate/2
, rather use number of items produce.
Comments
Post a Comment