Last Updated: August 15, 2017
·
5.603K
· nifoc

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!

4 Responses
Add your response

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 ·
over 1 year ago ·

binaryjoin([<<"a">>, <<"b">>, <<"1">>], <<".">>). % => <<"a.b.1">>
binary
join([<<"a">>, 1, <<"b">>], <<".">>). % => ** exception error: bad argument
binary_join([<<"a">>, <<"b">>, 1], <<".">>). % => <<"a.b">> !!!

over 1 year ago ·