string:join ?

Richard A. O'Keefe <>
Mon Jun 14 06:24:21 CEST 2004


Per Hedeland <> wrote:
	'man perlfunc' (ducking:-)

Erlang being a mostly-functional language, perhaps it would be more
appropriate to cite the Haskell version (and it would CERTAINLY be
clearer to use the Haskell name, because there are lots and lots and
LOTS of ways to 'join' strings):

unwords   :: [String] -> String
unwords [] = []
unwords ws = foldr1 (\w s -> w ++ ' ':s) ws

	join(List, Sep) ->
	    lists:foldl(fun(A, "") -> A;
			   (A, Acc) -> Acc ++ Sep ++ A
			end, "", List).
	
This is actually a perfect definition of why it would be good to have
it in the library.  Done right, it's O(size of result), done wrong, it's
very costly indeed, and this one is done wrong.

unwords(Words) -> unwords(Words, " ").

unwords([Word|Words], [])    -> unwords_0(Words, Word);
unwords([Word|Words], [Sep]) -> unwords_1(Words, Word, Sep);
unwords([Word|Words], Sep)   -> unwords_m(Words, Word, Sep);
unwords([],           _)     -> [].

% Special case for Sep = []
unwords_0([Word2|Words], Word1) -> Word1 ++ unwords_0(Words, Word2);
unwords_0([], Word1)            -> Word1.

% Special case for Sep = [_]
unwords_1([Word2|Words], Word1, Sep) ->
    Word1 ++ [Sep | unwords_1(Words, Word2, Sep)];
unwords_1([], Word1, _) -> Word1.

% General case for multi-element Sep.
unwords_m([Word2|Words], Word1, Sep) ->
    Word1 ++ (Sep ++ unwords_m(Words, Word2, Sep));
unwords_m([], Word1, _) -> Word1.



More information about the erlang-questions mailing list