Skip to content

Instantly share code, notes, and snippets.

@grantwinney
Last active April 1, 2021 04:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save grantwinney/1a6620865d333ec227be8865b83285a2 to your computer and use it in GitHub Desktop.
Save grantwinney/1a6620865d333ec227be8865b83285a2 to your computer and use it in GitHub Desktop.
Erlang utilities. Concatenates mixed list of values (binaries/strings/atom/integer/float) into a single binary or string.
-module(utils).
-export([concat/2]).
%% EXTERNAL
concat(Words, string) ->
internal_concat(Words);
concat(Words, binary) ->
list_to_binary(internal_concat(Words)).
%% INTERNAL
internal_concat(Elements) ->
NonBinaryElements = [case Element of _ when is_binary(Element) -> binary_to_list(Element); _ -> Element end || Element <- Elements],
lists:concat(NonBinaryElements).
%% EUNIT TESTS
-include_lib("eunit/include/eunit.hrl").
concat_conversion_test_() ->
[
{"list of strings to string", ?_assertEqual("This and that.", utils:concat(["This", " and", " that."], string))},
{"list of strings to binary", ?_assertEqual(<<"This and that.">>, utils:concat(["This", " and", " that."], binary))},
{"list of binaries to string", ?_assertEqual("This and that.", utils:concat([<<"This">>, <<" and">>, <<" that.">>], string))},
{"list of binaries to binary", ?_assertEqual(<<"This and that.">>, utils:concat([<<"This">>, <<" and">>, <<" that.">>], binary))},
{"mix of values to string", ?_assertEqual("This and that 5asdf hi.", utils:concat([<<"This">>, " and", <<" that ">>, 5, asdf, " hi."], string))},
{"mix of values to binary", ?_assertEqual(<<"This and that 5asdf hi.">>, utils:concat([<<"This">>, " and", <<" that ">>, 5, asdf, " hi."], binary))}
].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment