Reputation: 13672
I am currently forming strings from strings and binaries like this:
X = string:join(io_lib:format("~s~s~s", ["something1", "something2",<<"something3">>]), "") %X is now something1something2something3
This seems painful and messy. Because in order to dry this up with another such string with a different number of "~n":
Y = string:join(io_lib:format("~s~s", ["something1", <<"something2">>]), "")
I essentially have to write a function that counts the size of the argument list, and forms ~n[that many times]
and plugs it into this.
Is there a better way to be doing this?
Eshell V8.0.2 (abort with ^G)
1> F = <<"asdf">>,
1> string:join(io_lib:format("~s~s~s", ["something1", "something2", F]),"").
"something1something2asdf"
2> lists:flatten(["something1", "something2", F]).
[115,111,109,101,116,104,105,110,103,49,115,111,109,101,116,
104,105,110,103,50,<<"asdf">>]
3>
Upvotes: 1
Views: 389
Reputation: 245519
I'm confused as to why you need the call to io_lib:format
at all. It's not doing any work in this case.
string:join(["something1","something2","something3"], "").
Would give you the same result. You can simplify even further if there's really no separator character (and taking advantage of the fact that strings are just lists in Erlang):
lists:flatten(["something1", "something2", "something3"]).
Update
I see now that you're working with a list of different data types. While a one-liner may look pretty, you can see that they're not always flexible. In your case, I would create some mapper functions to handle mapping different types to strings. Maybe something like:
-module(string_utils).
-export([concat/1]).
to_string(Value) when is_binary(Value) -> binary_to_list(Value);
to_string(Value) -> Value.
concat(List) ->
lists:flatten(lists:map(fun to_string/1, List)).
And then your calling code would be:
string_utils:concat(["something1", "something2", <<"something3">>]).
Upvotes: 4