I have a problem with matching a variable number of bits in a binary, which I narrowed down to the following toy example to extract the first few bits of a binary:
f(<<H:Bits, _/binary>>, Bits) ->
H.
The compiler (R15B01) tells me variable 'Bits' is unbound. On the other hand, this works fine:
f(X, Bits) ->
<<H:Bits, _/binary>> = X,
H.
And it does what I expect, for instance f(<<1,2,3,4>>, 8) yields 1, and f(<<1,2,3,4>>, 16) yields 258.
Why doesn’t the first form work? Shouldn’t it be equivalent?
In your first example,
f(<<H:Bits, _/binary>>, Bits) -> H, the variable Bits is not previously bound – it occurs both the first and the second argument pattern, but they are not matched in any specific order, so Bits within the binary is considered to be unbound. In the second example,f(X, Bits) -> <<H:Bits, _/binary>> = X, Bits becomes bound before the matching of<<...>> = Xbegins.The first example could be read as “take the number Bits given in the second argument and extract that many bits from the binary as H” (what you wanted), but could also be read as “Grab some arbitrary number Bits of bits (perhaps as many as possible) from the binary as H, and then check that it happens to be the same number as the one passed in the second argument”. To avoid this ambiguity, the compiler rejects the program.