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

Ben Munat bent@REDACTED
Thu Sep 13 12:34:37 CEST 2007


ok wrote:
 > Otherwise, if what you are after is the Python join(words, sep)
 > function, you want the code below.  As you note, it isn't that hard
 > to write, but then, neither are most of the functions in the lists
 > and string modules.  This doesn't depend on the element type, so it
 > could go in the lists module, but considering its likely uses, it
 > probably belongs in the string module.
 >
 > %   join([X1,...,Xn], Sep) -> X1 ++ Sep ++ ... ++ Sep ++ Xn;
 > %   join([],          _)   -> [].
 > %   The intended type is join([[x]], [x]) -> [x].
 >
 > join([X|Xs], [])  -> join0(X, Xs);
 > join([X|Xs], [C]) -> join1(X, C, Xs);
 > join([X|Xs], Sep) -> join2(X, Sep, Xs);
 > join([],     _)   -> [].
 >
 > join0(X, [Y|Ys]) -> X ++ join0(Y, Ys);
 > join0(X, [])     -> X.
 >
 > join1(X, C, [Y|Ys]) -> X ++ [C|join1(Y, C, Ys)];
 > join1(X, _, [])     -> X.
 >
 > join2(X, Sep, [Y|Ys]) -> X ++ (Sep ++ join2(Y, Sep, Ys));
 > join2(X, _,   [])     -> X.

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)?

In other words "X ++ join(Y, Ys)" would evaluate the recursive calls to join() 
before being able to concatenate the result onto X... meaning keeping stuff on 
the stack for each call.

Am I right or misinterpreting the call structure?

thanks,

Ben





More information about the erlang-questions mailing list