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

David King <>
Wed Sep 12 19:51:25 CEST 2007


> i'm guessing they mean join in the scripting language sense which  
> is more for creating CSV type strings.
> ie (fictional function):
> "I,Like,Erlang" = lists:join(["I","Like","Erlang"],",")
> so join/2 would be something like (newbie alert, just started  
> learning erlang, so excuse the (possibly) bad code):
> join([First|Rest],JoinWith) ->
>    lists:flatten( [First] ++ [ JoinWith ++ X || X <- Rest] ).
> calling join(["A","B","C"],"+")
> would result in "A+B+C"

(Same learning-warning as above) List concatenations involve building  
new lists, which involves copying the old ones.

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


>
>
> On 9/12/07, igwan < > wrote:It does exist :
>
> erlang:'++'/2
>
> and the corresponding syntactic sugar :
>
> 1> [a,b,c] ++ [d,e,f].
> [a,b,c,d,e,f]
>
>
> -igwan
>
> Peter K Chan a écrit :
> > I looked around and I couldn't find a list:join() implementation for
> > erlang. Is this intentional? The join function seems to be a useful
> > feature to have.
> >
> > I ended up writing my own version, which was simple enough; but  
> it would
> > be even better if it is available as a BIF.
> >
> > Peter
> > _______________________________________________
> > erlang-questions mailing list
> > 
> > http://www.erlang.org/mailman/listinfo/erlang-questions
> >
>
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions




More information about the erlang-questions mailing list