我有一个元组列表:
X = [{"alpha","beta"},{"gamma","theta"}].
我想使用io_lib:format("~s", [X])
以下列格式打印X作为扁平字符串:
[{"x":"alpha", "y":"beta"}, {"x":"gamma", "y":"theta"}]
我如何实现这一目标?我开始使用Map来转换列表。但我无法将其打印为字符串...(在X上给出了未绑定的变量错误)。
答案 0 :(得分:2)
疯狂地看起来像JSON序列化! 您应该查看rfc4627.erl,因为它几乎完全符合您的要求。
答案 1 :(得分:2)
享受巧妙的技巧:
1> X = [{"alpha","beta"},{"gamma","theta"}].
2> F = fun(X) -> [[$,|H]|T] = [[$,|["{\"x\":\"",A,"\", \"y\":\"",B,"\"}"]] || {A,B} <- X], [$[,[H|T],$]] end.
#Fun<erl_eval.6.111823515>
3> io:format("~s~n", [F(X)]).
[{"x":"alpha", "y":"beta"},{"x":"gamma", "y":"theta"}]
请注意我在F
中执行的所有字符串操作都是O(1)。
答案 2 :(得分:0)
试试这个:
tuplelist_to_string(L) ->
tuplelist_to_string(L,[]).
tuplelist_to_string([],Acc) ->
lists:flatten(["[",
string:join(lists:reverse(Acc),","),
"]"]);
tuplelist_to_string([{X,Y}|Rest],Acc) ->
S = ["{\"x\":\"",X,"\", \"y\":\"",Y,"\"}"],
tuplelist_to_string(Rest,[S|Acc]).
然后:
1> X = [{"alpha","beta"},{"gamma","theta"}].
[{"alpha","beta"},{"gamma","theta"}]
2> io:format("~s~n",[test:tuplelist_to_string(X)]).
[{"x":"alpha", "y":"beta"},{"x":"gamma", "y":"theta"}]
ok
答案 3 :(得分:0)
你应该这样打印:
[{A,B},{G,T}] = X
io_lib:format(“[{x:~s,y:~s},{x:~s,y:~s}]”,[A,B,G,T])