[erlang-questions] Booleans in bit syntax

Viktor Söderqvist viktor@REDACTED
Sun Jan 21 03:14:30 CET 2018


The topic 1=true and 0=false as a convention seems to be controversial. :-)

If not adding booleans in bit syntax, then how about adding build-in
conversion functions for booleans and bit values? E.g. boolean_to_integer/1.

If we can't assume that convention, then how about adding four
functions: is_zero/1, is_one/1, true_count/1 and false_count/1 instead?
That should get rid of any confusion.

Theoretically, of course there are two possible bijective mappings
between bit values (0, 1) and boolean values (true, false).

It may be radical, but in practice, I believe the convention (1 for
true) can be safely assumed to be generally understood by almost
everyone in almost every such such mapping situation. Even persons who
doesn't have any insight in programming often have an intuition that it
is all about ones and zeroes, representing true/false, or electric
switch on/off; the bit as the smallest and most basic unit of
information in computers.

Replies to Jacob and Kostis inline.

On 2018-01-20 15:53, Jacob wrote:
> In my opinion, it changes much without really filling a gap. So far, the
> <<>> expressions/matches only convert numbers to binaries/bitstrings and
> vice versa.

Bit syntax can also convert between Unicode codepoints, UTF-8, UTF-16
and UTF-32. It can convert endianess for IEEE floats and integers too.
Pretty much any convenient conversion for basic types to/from binary.

    << <<X/utf16-little>> || <<X/utf8>> <= <<"Example">> >>.

On 2018-01-20 15:58, Kostis Sagonas wrote:
> Yes. The Erlang type language already has a type boolean() which is
> defined to comprise of the atoms 'true' and 'false'.

true and false are not just any atoms. They have special meaning in
language constructs for branching, i.e. logic. Arguably the most basic
values of all.

On 2018-01-20 15:53, Jacob wrote:
> What about
> 
>   decode_stuff(<<F1:1, F2:1, 0:6, Rest/binary>>) ->
>       {F1 =:= 1, F2 =:= 1, Rest}
> 
> it's even shorter than your proposal and already works (okay, encoding
> bools is a different thing).

You are right, the manual conversion is really just three tokens.

The simplest encoding I can think of would be a function call, given you
already have such a function in your module.

> I prefer to have explicit conversions, IMO they are much better to
> maintain than using conversion magic.

Doesn't the type specifier in the bit syntax indicate an explicit
conversion between binary and the explicitly specified type?

On 2018-01-20 15:58, Kostis Sagonas wrote:
> 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.

Isn't most of the binary syntax just syntactic sugar for conversions?

Viktor



More information about the erlang-questions mailing list