primalforma
primalforma

Reputation: 75

Generating String from List in Erlang

I'm trying to generate a formatted string based on a list:

[{"Max", 18}, {"Peter", 25}]

To a string:

"(Name: Max, Age: 18), (Name: Peter, Age: 35)"

Upvotes: 4

Views: 10564

Answers (4)

phus
phus

Reputation: 1

A simple but slow way:

string:join([lists:flatten(io_lib:format("(~s: ~p)", [Key, Value])) || {Key,Value} <- [{"Max", 18}, {"Peter", 25}]], ", ").

Upvotes: 0

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

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.

Upvotes: 0

user425720
user425720

Reputation: 3598

is it JSON?

use some already written modules in e.g mochiweb.

Upvotes: -1

YOUR ARGUMENT IS VALID
YOUR ARGUMENT IS VALID

Reputation: 2059

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.

Upvotes: 10

Related Questions