How do I change strings recursively adding a number to the string and adding each one to a list

Viewed 85

I am working on a project where I have to change a string and add it to a list.

Something like this:

def function(string, amount), do: "string + amount" end

where the amount is increasing until n.

The next step is to add this string to a list, so I'll receive:

[string1, string2,...., string]

How can I append this string recursively to the list based in the increased amount, using Elixir?

2 Answers

If I understood you well, you want a method that will accept a string and an integer, then return a list of n strings in the form "string + 1", "string + 2", ... "string + n".

If that's the case you could use Enum.map with a range:

defmodule StringHelper do
  def string_list(value, n) when n >= 1 do
    Enum.map(1..n, &"#{value} + #{&1}")
  end
end

example:

iex> StringHelper.string_list("foo", 5)
["foo + 1", "foo + 2", "foo + 3", "foo + 4", "foo + 5"]

You probably will be better off doing something like what @potibas suggested, but if you must do it recursively, you will need to keep an accumulator (the resulting list), and you will need to keep track of the current n. So, something like:

defmodule StringHelper do
  def string_list(value, n, acc \\ [])

  def string_list(value, n, acc) when n > 0 do
    string_list(value, n - 1, ["#{value}#{n}" | acc])
  end

  def string_list(_, _, acc), do: acc
end

Then you can use it like:

iex> StringHelper.string_list("hello", 5)
["hello1", "hello2", "hello3", "hello4", "hello5"]

notice that for n <= 0 this will always return an empty list, which could not be what you want

Related