Skip to content

Instantly share code, notes, and snippets.

@eiri
Created June 26, 2014 02:16
Show Gist options
  • Save eiri/4afe8a98966f06a576b1 to your computer and use it in GitHub Desktop.
Save eiri/4afe8a98966f06a576b1 to your computer and use it in GitHub Desktop.
Erlang's binary:join/1
join([], _) -> []; %% or should it be <<"">> for a consistency sake?
join([H|[]], _) -> H;
join(List, Sep) when is_list(Sep) ->
join(List, list_to_binary(Sep));
join([H|T], Sep) ->
join(T, H, Sep).
join([], Acc, _) ->
Acc;
join([H|T], Acc, Sep) ->
join(T, <<Acc/binary, Sep/binary, H/binary>>, Sep).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
join_test_() ->
List = [<<"a">>, <<"b">>, <<"c">>],
[
?_assertEqual(join(List, ", "), <<"a, b, c">>),
?_assertEqual(join(List, <<"|">>), <<"a|b|c">>),
?_assertEqual(join([<<"a">>], ", "), <<"a">>),
?_assertEqual(join([], ", "), [])
].
-endif.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment