sectoreye
sectoreye

Reputation: 33

How to Erlang binary combine?

Given

[<<"1 coin">>, <<"2 cash">>, <<"3 coin">>]

I want:

<<"1 coin, 2 cash, 3 coin">>

How can I accomplish this?

Upvotes: 2

Views: 333

Answers (1)

Pascal
Pascal

Reputation: 14042

The way to concatenate 2 binaries is <<B1/binary, B2/binary>>. It is not often used since list of binaries are generally so called iolist, and are directly manipulated by most libraries in Erlang.

As you not only want to flatten your list but also add those ", " between each terms, you can write your own recursive function or use the lists:foldl/3:

1> Concat = fun(L) -> [H|T] = lists:reverse(L), lists:foldl(fun(X,Acc) -> <<X/binary,", ",Acc/binary>> end, H, T) end.
#Fun<erl_eval.6.90072148>
2> Concat([<<"1 coin">>, <<"2 cash">>, <<"3 coin">>]).                                                                               
<<"1 coin, 2 cash, 3 coin">>
3>

Upvotes: 3

Related Questions