Elixir: generate a list of `n` occurrences of a given argument (similar to Haskell's replicate)
def replicate(n, x), do: for _ <- 1..n, do: x
If you want the last case to return string then you should add definition for this type using guard, something like this:
def replicate(n, [x]) when is_integer(x), do: to_string(for _ <- 1..n, do: x)
def replicate(n, x), do: for _ <- 1..n, do: x
iex(1)> replicate 3, 5
[5, 5, 5]
iex(2)> replicate 3, 'a'
"aaa"
You can also use String.duplicate/2 and List.duplicate/2 as other suggested:
def replicate(n, x = [c]) when is_integer(c), do: String.duplicate(to_string(x), n)
def replicate(n, x), do: List.duplicate(x, n)
Also please note that Char list 'a'
and String "a"
are different things in Elixir, so ensure you understand this correctly.
And finally if this is not a home task then I'd suggest not to reinvent bicycle but directly use functions from String and List module, when possible.