Erlang Central

String join with

Revision as of 04:30, 25 July 2007 by Khigia (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Problem

You need to combine several items of a list into a string using a separator between each item representation.

In python, this is done by:

python> ','.join(['a', 'b', 'c'])
'a,b,c'
python> ','.join(map(str, [1,2,3]))
'1,2,3'

Solution

This solution interleave the input list with as many copy of the separator, then use the builtin concat function to create the final string:

string_join(Join, L) ->
    string_join(Join, L, fun(E) -> E end).

string_join(_Join, L=[], _Conv) ->
    L;
string_join(Join, [H|Q], Conv) ->
    lists:flatten(lists:concat(
        [Conv(H)|lists:map(fun(E) -> [Join, Conv(E)] end, Q)]
    )).

Usage is as follow:

erl> test:string_join(",", ["1", "2", "3"]).
"1,2,3"
erl> test:string_join(",", [1, 2, 3], fun(X) -> io_lib:format("~B", [X]) end).
"1,2,3"