Skip to content

Instantly share code, notes, and snippets.

@unix1
Last active August 29, 2015 14:04
Show Gist options
  • Save unix1/49187e78302dcc663ff7 to your computer and use it in GitHub Desktop.
Save unix1/49187e78302dcc663ff7 to your computer and use it in GitHub Desktop.
Erlang stdlib provides string:join/2 function but not binary:join/2. Below are few options how to do binary:join/2. Guess which one is the fastest.
-module(binary2).
-export([joinl/2]).
-export([joinfl/2]).
-export([joinfr/2]).
% use list comprehension
joinl([], Sep) when is_binary(Sep) ->
<<>>;
joinl([H|T], Sep) ->
erlang:iolist_to_binary([H, [[Sep, X] || X <- T]]).
% use lists:foldl/3 followed by lists:reverse/1
joinfl([], Sep) when is_binary(Sep) ->
<<>>;
joinfl([H|T], Sep) ->
erlang:iolist_to_binary([H, lists:reverse(
lists:foldl(fun(X, Acc) -> [X|[Sep|Acc]] end, [], T))]).
% use lists:foldr/3
joinfr([], Sep) when is_binary(Sep) ->
<<>>;
joinfr([H|T], Sep) ->
erlang:iolist_to_binary([H|
lists:foldr(fun(X, Acc) -> [Sep|[X|Acc]] end, [], T)]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment