What is the preferred order for operands in boolean expressions? - boolean

Is there any benefit to structuring boolean expressions like:
if (0 < x) { ... }
instead of
if (x > 0) { ... }
I have always used the second way, always putting the variable as the first operand and using whatever boolean operator makes sense, but lately I have read code that uses the first method, and after getting over the initial weirdness I am starting to like it a lot more.
Now I have started to write all my boolean expressions to only use < or <= even if this means the variable isn't the first operand, like the above example. To me it seems to increase readability, but that might just be me :)
What do other people think about this?

Do whatever is most natural for whatever expression you are trying to compare.
If you're wondering about other operations (like ==) there are previous topics comparing the orderings of operands for those comparisons (and the reasons why).

It is mostly done to avoid the problem of using = instead of == in if conditions. To keep the consistency many people use the same for with other operators also. I do not see any problem in doing it.

Use whatever 'reads' best. One thing I'd point out is that if I'm testing to see if a value is within bounds, I try to write it so the bounds are on the 'outside' just like they might be in a mathematical expression:
So, to test that (0 < x <= 10):
if ((0 < x) && (x <= 10)) { ... }
instead of
if ((0 < x) && (10 >= x)) { ... }
or
if ((x > 0) && (10 >= x)) { ... }
I find this pattern make is somewhat easier to follow the logic.

An advantage for putting the number first is that it can prevent bug of using = when == is wanted.
if ( 0 == x ) // ok
if ( 0 = x ) //is a compiler error
compare to the subtle bug:
if ( x = 0 ) // assignment and not comparison. most likely a typo

To be honest it's unusual to write expressions with the variable on the right-side, and as a direct consequence of that unusualness readability suffers. Coding conventions have intrinsic value merely by virtue of being conventions; people are used to code being written in particular standard ways, x >= 0 being one example. Unnecessarily deviating from simple norms like these should be avoided without good cause.
The fact that you had to "get over the initial weirdness" should perhaps be a red flag.
I would not write 0 < x just as I would not use Hungarian notation in Java. When in Rome, do as the Romans do. The Romans write x >= 0. No, it's not a huge deal, it just seems like an unnecessary little quirk.

Related

Julia (JuMP): Indicator constraints with multiple conditional values (is a boolean expression possible?)

I want to implement a constraint depending on the change of values in my binary decision variable, x, over "time".
I am trying to implement a minimum operating time constraint for a unit commitment optimization problem for power systems. x is representing the unit activation where 0 and 1 show that a power unit, n, at a certain time, t, respectively is shut off or turned on.
For this, indicator constraints seem to be a promising solution and with the inspiration of a similar problem the implementation seemed quite straightforward.
So, since boolean operators are introduced (! and ¬), I prematurely wanted to express the change in a boolean way:
#constraint(m, xx1[n=1:N,t=2:T], (!x[n,t-1] && x[n,t]) => {next(t, 1) + next(t, 2) == 2})
Saying: if unit was deactivated before but now is on, then demand the unit to be active for the next 2 times.
Where next(t, i) = x[((t - 1 + i) % T) + 1].
I got the following error:
LoadError: MethodError: no method matching !(::VariableRef)
Closest candidates are:
!(!Matched::Missing) at missing.jl:100
!(!Matched::Bool) at bool.jl:33
!(!Matched::Function) at operators.jl:896
I checked that the indicator constraint is working properly with a single term only.
Question: Is this possible or is there another obvious solution?
Troubleshooting and workarounds: I have tried the following (please correct me if my diagnosis is wrong):
Implement change as an expression: indicator constraints only work with binary integer variables.
Implement change as another variable relating to x. I have found a solution but it is quite sketchy, which is documented in a Julia discourse. The immediate problem, found from the solution, is that indicator constraints do not work as bi-implication but only one way, LHS->RHS. Please see the proper approach given by #Oscar Dowson.
You can get the working code from github.
The trick is to find constraint(s) that have an equivalent truth-table:
# Like
(!x[1] && x[2]) => {z == 1}
# Is equivalent to:
z >= -x[1] + x[2]
# Proof
-x[1] + x[2] = sum <= z
--------------------------
- 0 + 0 = 0 <= 0
- 1 + 0 = -1 <= 0
- 0 + 1 = 1 <= 1
- 1 + 1 = 0 <= 0
I was recommended MOSEK Modeling Cookbook to help working out the correct formulation of constraints.
See eventually the thread here from where I got the answer for further details.

"Find the Parity Outlier Code Wars (Scala)"

I am doing some of CodeWars challenges recently and I've got a problem with this one.
"You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N."
I've looked at some solutions, that are already on our website, but I want to solve the problem using my own approach.
The main problem in my code, seems to be that it ignores negative numbers even though I've implemented Math.abs() method in scala.
If you have an idea how to get around it, that is more than welcome.
Thanks a lot
object Parity {
var even = 0
var odd = 0
var result = 0
def findOutlier(integers: List[Int]): Int = {
for (y <- 0 until integers.length) {
if (Math.abs(integers(y)) % 2 == 0)
even += 1
else
odd += 1
}
if (even == 1) {
for (y <- 0 until integers.length) {
if (Math.abs(integers(y)) % 2 == 0)
result = integers(y)
}
} else {
for (y <- 0 until integers.length) {
if (Math.abs(integers(y)) % 2 != 0)
result = integers(y)
}
}
result
}
Your code handles negative numbers just fine. The problem is that you rely on mutable sate, which leaks between runs of your code. Your code behaves as follows:
val l = List(1,3,5,6,7)
println(Parity.findOutlier(l)) //6
println(Parity.findOutlier(l)) //7
println(Parity.findOutlier(l)) //7
The first run is correct. However, when you run it the second time, even, odd, and result all have the values from your previous run still in them. If you define them inside of your findOutlier method instead of in the Parity object, then your code gives correct results.
Additionally, I highly recommend reading over the methods available to a Scala List. You should almost never need to loop through a List like that, and there are a number of much more concise solutions to the problem. Mutable var's are also a pretty big red flag in Scala code, as are excessive if statements.

Does Scala intelligently terminate calculating OR expressions for fold operations?

Suppose you have a value val list: List[Date]. You would like to know if any one of the dates in this list occur after some startDate. You could do this
list.fold(false)((a, b) => startDate.compareTo(b) < 0 || a)
which would return true if any date occurred on or after startDate thus achieving our objective.
However, since this is an OR statement being used, if even only one date satisfies the condition startDate.compareTo(b) < 0, then the whole fold operation will return true. Does Scala have a way of terminating execution of the fold and just returning the true when it hits it?
This sounds like a usecase for exists.
list.exists(a => startDate.compareTo(a) < 0)
https://www.scala-lang.org/api/current/scala/collection/immutable/List.html#exists(p:A=%3EBoolean):Boolean
However, since this is an OR statement being used, if even only one date satisfies the condition startDate.compareTo(b) < 0, then the whole fold operation will return true.
Actually, not necessarily; startDate.compareTo(b) < 0 could throw an exception. You'd need to change the order of operands to (a, b) => a || startDate.compareTo(b) < 0; even then it would be correct for a List, but not e.g. a Stream.
At any rate, as far as I know the answer is no even for the cases where it's correct. fold can't see inside the function it receives, only call it, so it would require specific support for this case in the compiler.
See also: Abort early in a fold and https://users.scala-lang.org/t/breaking-out-of-a-map-or-other-iteration/1091.

What is wrong with my understanding of Scala Sets?

Full disclosure: I am (was?) taking Coursera's Scala course but was stumped by the second assignment on Sets. I'm not looking for just the answers (which are easily obtainable) and would receive marginal credit anyway. But I would really like to understand what is happening.
Okay, so here is the first question: "Define a function which creates a singleton set from one integer value: the set represents the set of the one given element." So my first attempt was this:
def singletonSet(elem: Int): Set = Set(elem)
So this function, singletonSet, just returns a newly created Set. It could be invoked thusly:
val why = singletonSet(3)
// now why is a singleton set with a single integer, 3
This implementation seemed trivial, so I Googled for the answer, which seems to be this:
def singletonSet(elem: Int): Set = (x => x == elem)
Now my understanding is that (x => x == elem) is an anonymous function which takes an integer x and returns a boolean. But... what? So as a JavaScript developer, I decided to translate it:
function singletonSet(elem) {
return function(x) {
return x === elem;
};
};
So then I can write (am I currying?):
singletonSet(3)(4)
// singletonSet(3) => returns an anonymous function, function(x) { x === 3; };
// function(4) { return 4 === 3; }
// false
If this is even close to what is happening in Scala, it seems like I am not creating a singleton set. Rather, I am just checking if two numbers are the same.
What am I missing here? I feel like it must be something very basic.
Thanks in advance.
Remember this implementation of a set is a function. In particular its a boolean function, so the function can just be seen as asking the question: "Is this number in the set? - true or false." The function can be called as many times as you want, in effect asking the question multiple times:
"is this number in the set? Is that number in the set?" etc, etc.
As the set is a singleton set, there is only one number in the set. So you use the set by calling the function, asking the question, in effect, "is this number the one and only number that is in the set?" So you are correct this set, the singleton set is just asking are these two numbers the same.
It should be emphasised that this example is from the course Functional Programming Principles in Scala. The course is not meant as an easy introduction to Scala. In fact the course is deliberately making things difficult, in order to enable a deep understanding of functional programming. Normally one would just use the in scope immutable Set class.
If you wanted to work with say the even numbers between -1000 and 1000, you'd probably use an iterator like:
(-1000 to 1000).withFilter(_ %2 == 0)
or:
(-1000 to 1000 by 2)

In what circumstances can a compiler change the execution order of programme statements?

If this is not a real question then feel free to close ;)
Not only the compiler can reorder execution (mostly for optimization), most modern processors do so, too. Read more about execution reordering and memory barriers.
The compiler can change the execution order of statements when it sees fit for optimization purposes, and when such changes wouldn't alter the observable behavior of the code.
A very simple example -
int func (int value)
{
int result = value*2;
if (value > 10)
{
return result;
}
else
{
return 0;
}
}
A naive compiler can generate code for this in exactly the sequence shown. First calculate "result" and return it only if the original value is larger than 10 (if it isn't, "result" would be ignored - calculated needlessly).
A sane compiler, though, would see that the calculation of "result" is only needed when "value" is larger than 10, so may easily move the calculation "value*2" inside the first braces and only do it if "value" is actually larger than 10 (needless to mention, the compiler doesn't really look at the C code when optimizing - it works in lower levels).
This is only a simple example. Much more complicated examples can be created. It is very possible that a C function would end up looking almost nothing like its C representation in compiled form, with aggressive enough optimizations.
Many compilers use something called "common subexpression elimination". For example, if you had the following code:
for(int i=0; i<100; i++) {
x += y * i * 15;
}
the compiler would notice that y * 15 is invariant (its value doesn't change). So it would compute y * 15, stick the result in a register and change the loop statement to "x += r0 * i". This is kind of a contrived example, but you often see expressions like this when working with array indexes or any other base + offset type of situation.