Skip to content

Instantly share code, notes, and snippets.

@grantwinney grantwinney/utils.erl
Last active Sep 26, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.