August 23, 2024
P15 - Duplicate the elements of a list a given number of times.
Example:
> p15:duplicateN(3, ['a','b','c']).
[a,a,a,b,b,b,c,c,c]
erlang
%Duplicate the elements of a list a given number of times.
-module(p15).
-export([duplicateN/2]).
duplicateN(N, Ls) ->
lists:flatmap(fun(X) -> fill(N, X) end, Ls).
fill(0, Elem) ->
[];
fill(Value, Elem) ->
[Elem] ++ fill(Value - 1, Elem).