1
0
Fork 0
blog.kempkens.io/content/posts/2014-02-16-joining-a-list-of-binaries-in-erlang.md

34 lines
1,014 B
Markdown
Raw Permalink Normal View History

2014-03-23 19:40:19 +00:00
---
2021-08-28 19:50:49 +00:00
date: "2014-02-16T15:30:00Z"
description: Description and implementation of a function that joins a list of binaries.
tags:
- erlang
- programming
- english
slug: joining-a-list-of-binaries-in-erlang
2014-03-23 19:40:19 +00:00
title: Joining a List of Binaries in Erlang
---
The binary module in Erlang provides an easy way to split binaries using `split/2,3`, but what if you want to join a list of binaries back together?
There is no built-in function to do this, so I've decided to write my own.
2021-08-28 19:50:49 +00:00
{{< highlight erlang >}}
2014-03-23 19:40:19 +00:00
-spec binary_join([binary()], binary()) -> binary().
binary_join([], _Sep) ->
<<>>;
binary_join([Part], _Sep) ->
Part;
2014-07-14 19:32:28 +00:00
binary_join([Head|Tail], Sep) ->
lists:foldl(fun (Value, Acc) -> <<Acc/binary, Sep/binary, Value/binary>> end, Head, Tail).
2021-08-28 19:50:49 +00:00
{{< / highlight >}}
2014-03-23 19:40:19 +00:00
It works just like you would expect:
2021-08-28 19:50:49 +00:00
{{< highlight erlang >}}
2014-03-23 19:40:19 +00:00
binary_join([<<"Hello">>, <<"World">>], <<", ">>) % => <<"Hello, World">>
binary_join([<<"Hello">>], <<"...">>) % => <<"Hello">>
2021-08-28 19:50:49 +00:00
{{< / highlight >}}
2014-03-23 19:40:19 +00:00
Hope you find this useful!