[erlang-questions] list:join() for erlang?
Thu Sep 13 23:47:22 CEST 2007
On 9/13/07, David Terrell <> wrote:
> 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.
The above list comprehension flattens a list of list of lists, where
the longer version flattens a list of lists. It might be worth
benchmarking to see what the difference in performance characteristics
Obviously it's not a bottleneck in our software, or we'd have profiled
several different implementations by now.
More information about the erlang-questions