如何以递归方式更改字符串向字符串添加一个数字并将每个数字添加到列表中

Ale*_*Guz 3 recursion append elixir

我正在做一个项目,我必须更改一个字符串并将其添加到列表中。

像这样的东西:

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

其中数量增加直到 n。

下一步是将此字符串添加到列表中,因此我将收到:

[string1, string2,...., string]
Run Code Online (Sandbox Code Playgroud)

如何使用 Elixir 将此字符串递归地附加到基于增加的数量的列表中?

pot*_*bas 7

如果我理解你的话,你想要一个接受一个字符串和一个整数的方法,然后以“string + 1”、“string + 2”、...“string + n”的形式返回一个包含 n 个字符串的列表。

如果是这种情况,您可以将 Enum.map 与范围一起使用:

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

例子:

iex> StringHelper.string_list("foo", 5)
["foo + 1", "foo + 2", "foo + 3", "foo + 4", "foo + 5"]
Run Code Online (Sandbox Code Playgroud)