[erlang-questions] list:join() for erlang?

David Terrell dbt@REDACTED
Wed Sep 12 20:27:28 CEST 2007


On Wed, Sep 12, 2007 at 10:51:25AM -0700, David King wrote:
> A better idea is probably to build one that returns an iolist (since  
> if you're building a string, you're probably using it for io anyway),  
> like this:
> 
> join([ Head | [] ], _Sep) ->
>    [Head];
> join([ Head | Rest], Sep) ->
>    [Head,Sep | join(Rest,Sep) ].
> 
> util:join(["I","Like","Erlang"],"_") = ["I","_","Like","_","Erlang"].
> 
> You can always use lists:flatten/1 or erlang:iolist_to_binary/1 if  
> you need it flattened
> 
> That could maybe be optimised further to be tail-recursive using an  
> accumulator, but it doesn't involve building an entire list for every  
> entry

iolists can be arbitrarily deep, of course:

util:join([H], _Sep) -> [H];
util:join([H | T], Sep) ->
	[H | [[Sep, S] || S <- T]].
%% or   [H | lists:map(fun(S) -> [Sep, S] end, T)].

util:join(["I","Like","Erlang"],"_") = ["I",["_","Like"],["_","Erlang"]].

-- 
David Terrell
dbt@REDACTED
((meatspace)) http://meat.net/



More information about the erlang-questions mailing list