Joining A List Of Binaries In Erlang
The binary
module provides an easy way to split binaries using split/2,3
, but what if you want to join a list of binaries back together?
-spec binary_join([binary()], binary()) -> binary().
binary_join([], _Sep) ->
<<>>;
binary_join([Part], _Sep) ->
Part;
binary_join(List, Sep) ->
lists:foldr(fun (A, B) ->
if
bit_size(B) > 0 -> <<A/binary, Sep/binary, B/binary>>;
true -> A
end
end, <<>>, List).
It works just like you would expect:
binary_join([<<"Hello">>, <<"World">>], <<", ">>) % => <<"Hello, World">>
binary_join([<<"Hello">>], <<"...">>) % => <<"Hello">>
Hope you find this useful!
Written by Daniel Kempkens
Related protips
4 Responses
why not binary:list_to_bin/1
over 1 year ago
·
binary:list_to_bin/1
is just list_to_binary/1
… I feel like I'm missing something here. How would list_to_binary/1
do the same thing?
over 1 year ago
·
alternative
https://coderwall.com/p/746dgg
over 1 year ago
·
binaryjoin([<<"a">>, <<"b">>, <<"1">>], <<".">>). % => <<"a.b.1">>
binaryjoin([<<"a">>, 1, <<"b">>], <<".">>). % => ** exception error: bad argument
binary_join([<<"a">>, <<"b">>, 1], <<".">>). % => <<"a.b">> !!!
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Erlang
Authors
Related Tags
#erlang
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#