将整个列表转换为Erlang字符串

3pvhb19x  于 2022-12-08  发布在  Erlang
关注(0)|答案(4)|浏览(185)

我正在尝试执行以下操作

S = lists:concat(A) ++ " " ++ [254,874] ++ "\n".

它给我错误消息

** exception error: no match of right hand side value [51,50,52,51,53,54,53,54,55,54,54,53,52,51,32,254,874,10]

但它对字符串值“[254,874]”工作正常
我如何使[254,874]变为“[254,874]”

hmae6n7t

hmae6n7t1#

您可能忘记了f(S)用于上一次计算。请在使用命令之前尝试它:

1> f(S).
ok
2> S = lists:concat(A) ++ " " ++ [254,874] ++ "\n".

此外,您可以使用$[$]来表示ASCII中的"[" "]"

3> $[.
91
4> $].
93
5> S = lists:concat(A) ++ " " ++ [91,254,874,93] ++ "\n".
fcy6dtqo

fcy6dtqo2#

找到了答案

A = [254,876].
lists:flatten(io_lib:format("~p",[A])).

这将给出精确结果“[254,876]”

8ehkhllq

8ehkhllq3#

将整数列表转换为字符串
对于你的情况,我会做:

[A, B] = [254,876],
C = "[" ++ integer_to_list(A) ++ "," ++ integer_to_list(B) ++ "]".

对于更一般情况:

-module(l2s).
-compile(export_all).

list_to_string([H|List]) ->
    list_to_string(List, "[" ++ integer_to_list(H)).

list_to_string([], String) -> String ++ "]";

list_to_string([H | List], String) ->
    list_to_string(List, String ++ "," ++ integer_to_list(H)).

试验:

Eshell V7.3  (abort with ^G)
1> A = [1,2,3,4,5].
[1,2,3,4,5]
2> l2s:list_to_string(A).
"[1,2,3,4,5]"

相关问题