Erlang:转一个这样的列表:
[1,"aa","a1", 21]
成这样的字符串:
"(1, "aa", "a1", 21)".
如何做到这一点?
非常感激。
答案 0 :(得分:4)
你的问题是什么?
(fun(List) -> lists:flatten(["(", string:join([io_lib:format("~p", [I]) || I <- List], ", "), ")"]) end)([1, "aa", "a1", 21]).
答案 1 :(得分:3)
我认为你看起来像这样:
1> lists:flatten(["(",lists:foldl(fun (X, "") ->
io_lib:format("~p", [X]);
(X, Acc) ->
[Acc, ",", io_lib:format("~p", [X])] end,
"", [1,"aa","a1", 21]), ")" ]).
"(1,\"aa\",\"a1\",21)"
这就是了解理论家的一切。我们首先使用列表上的折叠创建内部零件的列表:
Inner = lists:foldl(fun (X, "") ->
io_lib:format("~p", [X]);
(X, Acc) ->
[Acc, ",", io_lib:format("~p", [X])] end,
"", [1,"aa","a1", 21]),
然后换行
Wrapped = ["(", Inner, ")"],
为了漂亮的打印,我们将列表展平为最终字符串:
lists:flatten(Wrapped).
按照惯例,我们然后插入表达式,制作一个大的,不可读的函数,如上所示:)