[erlang-questions] Bit syntax matching gotchas
Björn Gustavsson
bjorn@REDACTED
Fri Feb 5 06:02:12 CET 2016
On Fri, Feb 5, 2016 at 1:35 AM, Ameretat Reith <ameretat.reith@REDACTED> wrote:
> On Wed, 3 Feb 2016 07:17:02 +0100
> Björn Gustavsson <bjorn@REDACTED> wrote:
[...]
>> The reason I reject it is that the matching previously bound variables
>> is uncommon. Even in the compiler test suites it is uncommon (test
>> suites typically match bound variables more often than production code
>> do).
>
> Not that common but nothing prevents coder to write:
>
> update_token(NewToken, ID) ->
> case NewToken of
> <<Time:16, _:PrefLen/bytes, ID:Len/bytes>> when (Now-Time) < 60
> ...
>
> That looked logical to me and it took some time to understand I should
> change my code to:
>
> update_token(NewToken, ID) ->
> case NewToken of
> <<Time:16, _:PrefLen/bytes, ReceivedID/bytes>> when
> ReceivedID =:= <<ID:Len/bytes>>, (Now-Time) < 60
Your examples don't compile because of undefined variables.
Assuming that Len and PrefLen should be the same
variable, I don't see why you would need to change
from the first example to the second. It seems that
both of your examples would work if you fix the
unbound variables.
I did not write in may mail that matching of bound
variables will not work. I only wrote that we would not
add any automatic masking of integer values. That is,
the following example works fine:
t() ->
t(16#FF, <<16#FF>>).
t(A, Bin) ->
<<A:8>> = Bin.
In the following example there will be a badmatch exception:
t() ->
t(16#FFFF, <<16#FF>>).
t(A, Bin) ->
<<A:8>> = Bin.
Solution #2 that I rejected would have made the second
example match too.
/Björn
--
Björn Gustavsson, Erlang/OTP, Ericsson AB
More information about the erlang-questions
mailing list