Generating String from List in Erlang
I'm trying to generate a formatted string based on a list:
[{"Max", 18}, {"Peter", 25}]开发者_JAVA百科
To a string:
"(Name: Max, Age: 18), (Name: Peter, Age: 35)"
The first step is to make a function that can convert your {Name, Age} tuple to a list:
format_person({Name, Age}) ->
lists:flatten(io_lib:format("(Name: ~s, Age: ~b)", [Name, Age])).
The next part is simply to apply this function to each element in the list, and then join it together.
format_people(People) ->
string:join(lists:map(fun format_person/1, People), ", ").
The reason for the flatten is that io_lib returns an iolist and not a flat list.
If performance is important, you can use this solution:
format([]) -> [];
format(List) ->
[[_|F]|R] = [ [", ","(Name: ",Name,", Age: ",integer_to_list(Age)|")"]
|| {Name, Age} <- List ],
[F|R].
But remember that it returns io_list() so if you want see result, use lists:flatten/1
. It is way how to write very efficient string manipulations in Erlang but use it only if performance is far more important than readability and maintainability.
A simple but slow way:
string:join([lists:flatten(io_lib:format("(~s: ~p)", [Key, Value])) || {Key,Value} <- [{"Max", 18}, {"Peter", 25}]], ", ").
is it JSON?
use some already written modules in e.g mochiweb.
精彩评论