Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)"
like image 912
primalforma Avatar asked Feb 25 '23 19:02

primalforma


1 Answers

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.

like image 110
YOUR ARGUMENT IS VALID Avatar answered Mar 01 '23 10:03

YOUR ARGUMENT IS VALID