Created
June 26, 2014 02:16
-
-
Save eiri/4afe8a98966f06a576b1 to your computer and use it in GitHub Desktop.
Erlang's binary:join/1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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