如何将值添加到已创建的列表中?

时间:2016-10-18 14:15:44

标签: erlang

我一直试图完成这项工作,但我不能,我希望实现这样的目标:

示例输入:[1,2,3,4]

示例输出:[“0”,“1”,“2”,“4”]

Data_list = Unknown_list_of_numbers,
Final_list = ["zero"],
lists:foreach(
    fun(Number) ->
      case Number of
        1 ->
            Final_list.append("one");
        2 ->
            Final_list.append("two");
        %% Few more case clauses %%
      end
    end,
    Data_list
),
function_to_do_something_with_name_of_numbers(Final_list).

1 个答案:

答案 0 :(得分:1)

为什么不为此使用lists:map

my_function(Input) -> F=fun(X) -> case X of 1 -> "one"; 2 -> "two"; 3 -> "three"; % and so on... you get the idea _ -> "-" end end, lists:map(F, Input). 遍历列表的所有元素并将函数应用于元素。它可能看起来像这样:

Input=[1,2,3,4,5,6,7,8].
["zero"] ++ my_function(Input).

这将是您的核心逻辑。要将结果添加到现有列表,只需使用'++'运算符附加它:

++

但要小心,{{1}}运算符在使用naiveley时会遇到严重的性能问题(它基本上会在附加之前处理左侧列表的所有条目)。如果你想使用iterativeley(一遍又一遍地创建一个列表),你最好先积累然后反转,请参阅this question以澄清......

相关问题