[erlang-questions] Construct and match binaries
Tue Nov 6 23:25:28 CET 2012
I'm not a language-lawyer, but will give it a try.
# Olav Frengstad 2012-11-06:
> I'm trying to wrap my head around a problem I have with constructing
> and matching a binary.
> Take the following example (will fail with "a binary field without
> size is only allowed at the end of a binary pattern"):
> 2> A = <<$a>>, B = <<$b>>,
> 2> <<A/binary, $:, B/binary>> = <<"a:b">>.
> * 2: a binary field without size is only allowed at the end of a binary pattern
You're performing pattern matching here, no term construction takes place. The
LHS thing is a prescription of expected shape of the RHS thing. First step that
would have to take place to evaluate it would be to fetch X/binary prefix (I'm
using X instead of A, because comparing against the value already in A would be
the next step to evaluate -- we're not there yet!), but we don't know how long
it is supposed to be, so the evaluator/compiler gets confused -- surely you
didn't mean to consume all RHS binary into X, obviously leaving $: and B/binary
with nothing to match against. This seems about the only interpretation that
offers itself for X/binary anywhere but at tail position, an it is clearly
> Using size specification yields the expected result:
> 3> <<A:1/binary, $:, B:1/binary>> = <<"a:b">>.
That's better, we first fetch X:1/binary and than compare against what has
previously been bound to A. It matches, good, let's proceed with the rest,
following the same steps. Oh good, all matches, success!
> Even equality checks works:
> 4> <<A/binary, $:, B/binary>> == <<"a:b">>.
Here you build up a new term on LHS, the sizes of A/binary and B/binary things
are implied -- they're binary or bitstrings values, these know their own size,
so no need to force programmer to overspecify things, he/she wouldn't even know
the size statically in many cases. Then you build up the RHS value (this is
constant, so no need to do anything at runtime if it were compiled code, but
that is a detail) and call builtin compare_for_equality(Lhs, Rhs), the name
is made up and since "==" is just syntactic sugar for function vall, I'm not
even sure the order of evaluation is even defined here, my choice of LTR is
just an example.
> I would assume that the size of the binary is known when performing
> construction and therefore the first example should work (considering
> <<X/binary,...>> equality checks works).
> Can anyone shed some light on what's happening here?
The second one is a construction, the first one is actually the opposite of
that... "deconstruction" maybe, "destruction" sounds a bit sinister and to
my understanting indeed means that too :-), but I'm not a native English
More information about the erlang-questions