def replicate(n, x), do: for _ <- 1..n, do: x
If you want the last case to return a string, you must add a 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 , like others:
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 note that Char list 'a' and String "a" two different things in Elixir, so make sure you get it right.
And finally, if this is not a homework task, I suggest not to reinvent the wheel, but to use functions from the String and List module, when possible.