Advanced Logic

Advanced logic operations

by Reinhard Grafl, creator of EV3 Basic

Motivation

In Small Basic (and indeed in any dialect of Basic, I have encountered) the use of comparators and of the logic operators AND and OR is limited to the context of If and While. But sometimes it is necessary to keep the outcome of a comparison for future use. For this you have to write something like

If X<10 OR X>50 Then
   A = "True"
Else
   A = "False"
EndIf

But knowing other programming languages you would probably very much prefer to write this in a single line like

A = X<10 OR X>50

which is not possible in Small Basic.

But using the Byte.ToLogic command, there is a funky way to indeed do the same thing also in one line. Please read on.

Comparators outside If and While

When reading the specification for the Byte.ToLogic commands carefully you can see that it will return "True" for positive input values and "False" for 0 or negative. So consider the following construct.

A = Byte.ToLogic(X-Y)

This will actually set A to "True" whenever X is greater than Y just like a non-existent greater-than comparison expression would. Similarly the construct

A = Byte.ToLogic(Math.Abs(X-Y))

is equivalent to a non-equal operator. Using this idea you can create all possible comparison expressions of Small Basic (some are quite simple to write, others are more complicated)

  X > Y              Byte.ToLogic(X-Y)
  X < Y              Byte.ToLogic(Y-X)
  X >= Y             Byte.ToLogic(1+Math.Floor(X-Y))
  Y <= X             Byte.ToLogic(1+Math.Floor(Y-X))
  X <> Y             Byte.ToLogic(Math.Abs(X-Y))
  X = Y              Byte.ToLogic(1-Math.Ceiling(Math.Abs(X-Y)))

Putting comparators together

To allow a logic combination of comparators (just like the motivating example), you can actually use the Math.Max and Math.Min commands to do proper AND and OR of the comparator outcomes. Consider the following example:

A = Byte.ToLogic(Math.Max(10-X,X-50))

The first parameter of the Max will be greater than zero whenever X is lower than 10. The second parameter of the Max will be greater than zero whenever X is higher than 50. The outcome of the Max command will be greater than zero whenever one of its parameters is greater than zero. By turning this "greater-than-zero" property into an explicit logic value of "True" or "False" with the Byte.ToLogic command, this is now totally equivalent to the non-existing construct:

A = X<10 OR X>50

all done in one single line. Here is a summary of logic operators (including NOT for good measure):

  A AND B                Math.Min(A,B)
  A OR B                 Math.Max(A,B)
  NOT A                  (1-Math.Ceiling(A))
Comments