[erlang-questions] Unexpected list_to_binary behavior

Richard A. O'Keefe ok@REDACTED
Wed Mar 19 02:13:21 CET 2014

On 19/03/2014, at 3:15 AM, Valentin Micic wrote:
> So, why should the other one be called: list_to_binary/1 instead instead of characters_to_binary/1

Because it converts a list of BYTES to a binary,
and *doesn't* convert a list of characters to a binary.
list_to_binary/1 is the opposite of binary_to_list/1.

We do need ways to build binaries from data that never were
characters to begin with!
> If one disregard the existence of any previous knowledge, and given that a list may contain any number of arbitrary types, including a list itself,  what should be a reasonable expectation for (and here's the kicker -- not an input argument itself, for it is perfectly acceptable to assume it to be a list, but) a content of the input argument?

How about "a reasonable expectation is what the documentation says"?

From the documentation for the 'erlang' module:

    list_to_binary(IoList) -> binary()


    IoList = iolist()
    Returns a binary which is made from the integers and binaries in IoList.

where iolist() is defined as
    maybe_improper_list(byte() | binary() | iolist(), binary() | [])

> It's surprising (at least was to me) to expect a content of an input argument ( formerly known as list )

The argument has been called IoList for some time.

> to be limited to a list of octets,

It isn't.  It's limited to a tree whose leaves are byte values,
binaries, or the empty list, and where [X|Y] is taken as

Why would it be surprising for a function to work the
way it is documented?
> On the other hand, it is what it is, and, in a way,  I am quite embarrassed that I assumed that integers would be automagically converted to appropriate number of octets, for this is just as unreasonable and arbitrary expectation.

binary_to_list/1 has no way to tell what an "appropriate number
of octets" might be.  You can whip up whatever you want in a
very few lines using bit syntax.

More information about the erlang-questions mailing list