Erlang:像这样翻一个列表:
[1,"aa","a1", 21]
变成这样的字符串:
"(1, "aa", "a1", 21)".
如何才能做到这一点?
非常感谢。
你的问题是什么?
(fun(List) -> lists:flatten(["(", string:join([io_lib:format("~p", [I]) || I <- List], ", "), ")"]) end)([1, "aa", "a1", 21]).
我认为您正在寻找这样的东西:
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)"
这都是关于理解 iolists 的。我们首先使用折叠列表创建内部零件列表:
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).
按照惯例,我们然后插入表达式,形成一个大的、不可读的函数,如上所示:)