[erlang-questions] bit syntax: what does "<<1234>> =" match?
Sat Feb 26 21:43:05 CET 2011
Le 26 févr. 2011 à 20:28, Robert Virding a écrit :
> ----- "Loïc Hoguin" <> wrote:
>> On 02/26/2011 06:04 PM, Anthony Ramine wrote:
>>> Le 26 févr. 2011 à 17:37, Anton Lebedevich a écrit :
>>> As I said, the thing on the left is a pattern, so I think it actually compiles to
>>> "a binary which the only byte's value is 1234", which obviously won't ever match
>>> That could be the intended behaviour as much as it could be a bug, IMHO.
>> What about this:
>> 9> <<1234:8>> = <<1234:8>>.
>> ** exception error: no match of right hand side value <<"Ò">>
>> 10> <<1234:16>> = <<1234:16>>.
> The behaviour is not a bug, it is rather an effect of how the expression is evaluated. The first thing to be aware of is that expressions in the shell are not compiled but are interpreted, done in the module erl_eval. This explains any differences between compiled code and the shell.
> In this case Anton is close. When tryin to match a binary the matcher first uses the bitspecs in the binary pattern to extract a value, then it tries to match it against the value given in the pattern.
> In the first case it extracts the first 8 bit integer from the binary, 210, and tries to match it against 1234, which fails. In the second it extracts the first 16 bit integer, 1234, which suceeds. If the pattern had been <<12.34/float>> it would have extracted the first 64 bits as a float and tried to match it against 12.34.
> One of the cool things with binaries is that there is no info in the binary saying how it was created so I can do lots of fun things when I pull it apart.
While it may be cool, I think the compiler should issue a warning when an impossible pattern is encountered. 1234 is obviously not representable with only 8 bits.
More information about the erlang-questions