[erlang-questions] list:join() for erlang?
Thu Sep 13 01:00:50 CEST 2007
On 13 Sep 2007, at 4:26 am, Peter K Chan wrote:
> Sorry that I made an omission.
> I was referring to the variant of join which takes a separator. For
> example: lists:join("abc", "/"), which evaluates to "a/b/c".
Should that have been join(["a","b","c"], "/")?
There are filename:join/2 and filename:join/1 functions which come
close to what you want, but they are specialised to file names and
do stuff you may not want. On the other hand, if, as the slash
suggests, you are pasting file names together, then filename:join/1
is EXACTLY what you want.
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.
More information about the erlang-questions