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

问题描述

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

类似这样的东西:

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

金额一直增加到n。

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

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

如何使用Elixir以增加数量将该字符串递归添加到列表中?

解决方法

如果我对您的理解很好,那么您需要一个可以接受字符串和整数的方法,然后以“字符串+ 1”,“字符串+ 2”,...“字符串+”的形式返回n个字符串的列表。 n”。

如果是这种情况,则可以将Enum.map用于范围:

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

示例:

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

做类似@potibas建议的操作可能会更好,但是如果必须递归执行,则需要保留一个累加器(结果列表),并且需要跟踪当前n。因此,类似:

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

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

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

然后您可以像使用它一样

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

请注意,对于n