String join with
From Erlang Community
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 example |
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:
Erlang code |
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:
Erlang example |
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"
|

Digg It
Del.icio.us
Reddit
Facebook
Stumble Upon
Technorati

