nmajna
Last Updated: August 15, 2017
·
3.057K
· nifoc
Avatar

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!

Say Thanks
Respond

4 Responses
Add your response

11843
Fda2927dafa7525b9e0916951e94f6cc

why not binary:list_to_bin/1

over 1 year ago ·
11855
Avatar

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 ·
28534
10 months ago ·
29195

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

4 months ago ·