Have you ever written a statement like this:
if n = 1 then m = 1 else m = 0 and then (assuming both are boolean) felt a bit silly for not writing
m = n?
What about
if n = 1 then m = 0 else m = 1? Would you feel equally silly (again assuming both are boolean) for not writing it as
m = 0-n?
Did you know that you can use the results of relational comparisons to feed into further logic?:
if (m>0) and (n=4) then print "Wha!" and that multiplication can be used like the logical AND, and sometimes even reduce the number of operations? (
a*b is the same as
a and b) Did you know that addition does the same for logical OR?
This is just a tiny peak into the world of mathematical conditions. Sometimes they are faster than conditional statements, sometimes they are slower, but overall I find it a lot of fun to try and condense something that would usually take several lines into one expression. It's become sort of a hobby within a hobby for me.
Sometimes you can come up with code that's very useful by doing this, especially if the result of the condition is simply to assign a value.
I'll follow with some examples I think are particularly pleasing:
Perhaps the simplest, but nonetheless elegant, example I can think of is toggling a value between 1 and 0:
n = 1-n.
A common problem, probably the first problem you face as a new coder, is to manage key presses; the challenge is usually to extract one instance of a key press from a key being held down. The common solution is called a "trip switch": because it only fires once until it is reset (in this case when the key is released) like a circuit breaker in a fuse box. The usual code is like so:
oldkey = newkey
newkey = keystate(x)
if newkey>oldkey then ...
I used this for a very long time until discovering a mathematical solution:
k = keystate(x) * (k + 1). The "+1" is very important here, it's what allows the switch to activate (k=1) in the first place (since on compile k=0), but upon the next test "+1" comes into play again and increments k. As long as key x is being held k will continue to count upwards, and so it can be used as a simple "trip"
if k=1 and the incremental values can also be utilised, but when key x is released it pulls the rug under k and wipes its value.
Wrapping a values to stay within a certain range is another fairly common need. For angles we have WRAPVALUE but for different ranges it can be tricky for newcomers. Here's a mathematical solution for ranges with a lower limit of 0:
Let n equal the subject variable, Let b equal the upper limit
n = ((n < 0) + (n / b - int(n / b))) * b
and for any lower limit I added a few extra assignments to help the processor:
Let n equal the subject variable, Let a equal the lower limit, Let b equal the upper limit
n = n - a : b = b - a
n = ((n < 0) + (n / b - int(n / b))) * b + a