[erlang-questions] Booleans in bit syntax
Kostis Sagonas
kostis@REDACTED
Sat Jan 20 15:58:44 CET 2018
On 01/20/2018 02:32 PM, Viktor Söderqvist wrote:
> Adding a boolean type specifier in the bit syntax would be useful, I
> think. Then you could write
>
> decode_stuff(<<Flag1/boolean, Flag2/boolean, 0:6, Rest/binary>>) ->
> {Flag1, Flag2, Rest}.
>
> instead of
>
> decode_stuff(<<F1:1, F2:1, 0:6, Rest/binary>>) ->
> Flag1 = case F1 of 1 -> true;
> 0 -> false
> end,
> Flag2 = case F2 of 1 -> true;
> 0 -> false;
> end,
> {Flag1, Flag2, Rest}.
>
> Many binary protocols contain flags and indicators, typically used as
> booleans in application logic with 1 for true, 0 for false.
>
> The default size would be 1 bit, i.e. Size = 1 and Unit = 1. It would be
> for constructing binaries as well. It is intuitive and it would be
> backward compatible.
>
> What do you think? Any reason for not adding it?
Yes. The Erlang type language already has a type boolean() which is
defined to comprise of the atoms 'true' and 'false'.
Suddenly adding some syntactic sugar which transforms 1s to trues and 0s
to falses in binaries does not add any significant expressive power to
the language; just confusion.
By the way, your "instead of" code is just bad programming. The
following is shorter and nicer:
decode_stuff(<<F1:1, F2:1, 0:6, Rest/binary>>) ->
{bit2bool(F1), bit2bool(F2), Rest}.
bit2bool(1) -> true;
bit2bool(0) -> false.
Kostis
More information about the erlang-questions
mailing list