RockyMountainHigh
RockyMountainHigh

Reputation: 3031

Erlang lists:flatten with one element

Why does erlangs lists:flatten not return a list if the nested list it takes only have one element in it.

Example:

DeepList = [[],[],["ONE"],[],[]].
[[],[],["ONE"],[],[]]
lists:flatten(DeepList).
"ONE"

This makes my following sequence difficult that contains a lists:foreach because it sees "ONE" as a list and tries to iterate over that. I'm sure I'm missing a better way of doing this. Any guidance would be greatly appreciated.

Upvotes: 1

Views: 580

Answers (1)

zxq9
zxq9

Reputation: 13164

"ONE" is also a list (of integers which happen correspond to printable character values in this case).

You wouldn't be surprised if you saw this:

1> lists:flatten([[],[],[1,2,3],[],[]]).
[1,2,3]

Now check this out:

2> lists:flatten([[],[],[79,78,69],[],[]]).
"ONE"

Usually it is easier (and much more efficient) to deal with "string" data as binaries:

3> lists:flatten([[],[],<<"ONE">>,[],[]]). 
[<<"ONE">>]

The "much more efficient" part comes from other operations you will probably be doing over the binary data (like matching, splitting, etc.) as well as the drastically reduced memory footprint of binaries.

Edit

I forgot to mention the power of string:join/2 in combination withstring:tokens/2 in this case:

4> string:tokens(string:join([[],[],"ONE",[],[]], " "), " ").
["ONE"]
5> string:tokens(string:join([[],[],"ONE",[],"Two"], " "), " ").
["ONE","Two"]

But... while that is a nifty hack, it suffers from every bad aspect of being a hack (its ugly, unclear, doesn't say what you mean, is noob unfiendly, and is massively less efficient than dealing with binaries).

Upvotes: 2

Related Questions