[erlang-questions] list:join() for erlang?
Thu Sep 13 22:38:29 CEST 2007
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.
> > 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) ->
join(Strings, Separator) ->
lists:flatten(revjoin(lists:reverse(Strings), Separator, )).
revjoin(, _Separator, Acc) ->
revjoin([S | Rest], Separator, ) ->
revjoin(Rest, Separator, [S]);
revjoin([S | Rest], Separator, Acc) ->
revjoin(Rest, Separator, [S, Separator | Acc]).
More information about the erlang-questions