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

David Terrell <>
Thu Sep 13 23:39:33 CEST 2007


On Thu, Sep 13, 2007 at 01:38:29PM -0700, Bob Ippolito wrote:
> On 9/13/07, David Mercer <> wrote:
> > On Thursday, September 13, 2007, Ben Munat wrote:
> > > Out of curiosity -- still feeling my way around erlang and functional
> > > programming -- aren't the "helper" functions here stack-recursive (i.e.
> > *not*
> > > tail-recursive)?
> >
> > Looks like you're right.  Here's my tail-recursive version of the same:
> >
> >         join([], _) -> [];
> >         join([S1 | S_Rest], Sep) ->
> >                 S1 ++ reverse_join(lists:reverse(S_Rest), Sep, []).
> >
> >         reverse_join([], _, Joined) -> Joined;
> >         reverse_join([S1 | S_Rest], Sep, Joined) ->
> >                 reverse_join(S_Rest, Sep, Sep ++ S1 ++ Joined).
> 
> Using ++ all over the place is probably a bad idea, at least according
> to the performance guide and my intuition. I haven't profiled it.
> 
> This is our join/2, which is largely the same but uses lists:flatten/1
> instead of ++:
> 
> join([], _Separator) ->
>     [];
> join([S], _Separator) ->
>     lists:flatten(S);
> join(Strings, Separator) ->
>     lists:flatten(revjoin(lists:reverse(Strings), Separator, [])).

Is there any reason to prefer that over:
join([H|T], Sep) ->
    lists:flatten([H | [[Sep, X] || X <- T]]).

list comprehensions rule.

-- 
David Terrell

((meatspace)) http://meat.net/



More information about the erlang-questions mailing list