Elixir: generate a list of "n" occurrences of the given argument (similar to Haskell replication)

I need an Elixir function to create a list of n occurrences of an argument similar to the Haskell replicate function :

 Input: replicate 3 5 Output: [5,5,5] Input: replicate 5 "aa" Output: ["aa","aa","aa","aa","aa"] Input: replicate 5 'a' Output: "aaaaa" 

I created a function to "replicate" integer n times:

 import String def replicate(number, n) String.duplicate(to_string(number), n) |> split("", trim: true) |> Enum.map(fn n -> String.to_integer(n) end end 

But this does not meet the specification :( Could you help me?

+5
source share
1 answer
 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.

+6
source

Source: https://habr.com/ru/post/1261959/


All Articles