How does a missing boolean operator still compile? - scala

I have code like this:
val pop: Bool = (
(fsm === Fsm.None && canPop) ||
(fsm === Fsm.Some && canPop && fooBar)
(fsm === Fsm.Other && canPop && dragonFruit) ||
(fsm === Fsm.Mom && canPop))
fsm is a ChiselEnum based state machine and the other signals are just Bools. There is a missing || on the second statement line (after fooBar). This compiles and runs, although causes a bug in the behavior. My question is... why does this compile? This doesn't seem like valid syntax. Is it?
Please help me understand this. I just spent numerous days debugging a large circuit to find this issue.

Correct Answer
The problem is that this is a bit extract. Chisel lets you do foo(bar) to extract the bit at index bar out of foo. The above code, as written, is a bit extract even though the user wants it to be a mistake.
Unfortunately, this is a known gotcha and it's not reasonable to error on this without false positives while still allowing users to use the () syntax for bit extracts.
Incorrect Original Answer
It's valid syntax per Scala rules. What's going on here is that the code is really two statements, but the indentation is confusing. It's equivalent to:
val foo = a + b // Create an immutable value equal to "a + b".
c + d // A bare statement that adds "c + d", but doesn't use the result.
Or infamous C bugs like:
if (cond)
foo();
bar(); // bar() is always executed, but the indentation is confusing.
Usually this is the type of thing that you'd notice due to a code formatter or via linting. However, the problem is common to almost every language.
Setting up Scalafmt for your project may help.

Related

Why do I get this compiler error with the djb2 hash function

I copied and pasted the widely available code for the djb2 hashing function, but it generates the error shown below (I am using the CS50.ide, which may be a factor). Since this error IS fixed by a second set of parentheses, can someone explain why those aren't in the code I find everywhere online?
dictionary.c:67:14: error: using the result of an assignment as a condition without
parentheses [-Werror,-Wparentheses]
while (c = *word++)
~~^~~~~~~~~
dictionary.c:67:14: note: place parentheses around the assignment to silence this
warning
while (c = *word++)
^
( )
dictionary.c:67:14: note: use '==' to turn this assignment into an equality comparison
while (c = *word++)
^
==
= is used for setting variables to a value. == is the relational operator used for comparing the equality of values. Perhaps you are finding the C++ version of the function. Perhaps it is the IDE compiler rules/config.+
I understand about = vs ==. My question was how come i get the compiler error with code that is correct, since it is a well established hash function.
turns out is related to the cs50 makefile being more stringent than clang on it's own. needlessly frustrating.

Slick "for/yield"-query doesn't compile with negative comparison

I ran into an odd problem with my slick-query:
As you can see, the function below is compiling although it's basically the same query but with a possitive comparison (I don't know if it's actually doing what it's supposed to do, though). When swapping the order of the if conditions, it tells me that && cannot be resolved. I don't know if that's the case, but I guess the second table query object, in this case contents, doesn't seem to be finished yet. However, that begs the question why the second function/query is compiling properly.
Do you have an answer to this? Am I doing something wrong here?
Thanks in advance!
You should use =!= for inequality and === for equality in queries according to slick docs
I guess I've fixed the problem.
Instead of:
if a.documentId === documentId && b.contentTypeId !== ContentType.PROCESS
I needed to write:
if a.documentId === documentId && !(b.contentTypeId === ContentType.PROCESS)
Still a weird behavior I can't really explain, espacially since negative comparisons like !== are generally allowed in those if-statements

object == nil or nil == object to check whether an object is nil?

While checking whether an object is nil, someone use 1:
if (object == nil) {
//...
}
someone use 2:
if (nil == object) {
//...
}
Any difference between 1 and 2? Which one is better?
The difference is mainly that if you mistakingly forget a = e.g like this
(nil = myObject)
you will get an error cause you can't assign a value to nil. So it is some kind of faile-safe.
The use of nil == object is actually an idiom to prevent the unlucky case where you miss a = in your expression. Example, you want to write:
if (object == nil)
but write:
if (object = nil) {
this is a typical error and one that is very difficult to track down, since the assignment has also a value as an expression and thus the condition will evaluate to false (no error), but you will also have wiped out your object...
On the other hand, writing
if (nil == object)
you ensure that that kind of error will be detected by the compiler since
if (nil = object)
is not a regular assignment.
Actually, modern compilers (default settings) will provide a warning for the kind of "unintended" assignment, ie:
if (object = nil) {
will raise a warning; but still this can be tricky.
As others pointed out, they are equivalent. There is also another way to do it:
if (!object) {
// object is nil
}
The reason some developers prefer "Yoda conditionals" is that it's less likely to inadvertently write if (object = nil) (note the assignment).
This is not an issue any more since compilers warn when assigning in a conditional expression without extra parentheses.
Since Yoda conditionals are less readable they should be avoided.
They are equivalent. Back in the days it was common to write if (CONST == variable) to reduce the risk of accidental assignment. E.g. if (variable = CONST) would assign a constant to the variable and the if-statement would evaluate as true or false depending on the value of the constant, not the variable.
Nowadays, IDEs and compilers will usually be smart enough to issue a warning on such lines. And many people prefer the first version due to readability. But really it's a matter of style.
best practice when using the comparison operator == is to put the constant on the left of the operand. in this way it is impossible to accidentally mistype the assignment operator instead of the comparison.
example:
( iVarOne == 1 )
is functionally equal to
( 1 == iVarOne)
but
( iVarOne = 1 )
is much different than
( 1 = iVarOne )
this best practice works around the fact that compilers do not complain when you mistype an assignment for a comparison operator...
Nope, only in readability I prefer the first one, while some other developers may prefer the other.
Its just a coding style issue, it has no technical difference at all.
Some may say that the second is better, since it is more explicit, the nil comes first so its easier to note that we are testing for nil, but again it depends on the developer taste.
There is no difference at all. It's all about readability. If you want to write a clean code, you should take care of this.
If you place the "Object" to the right of the evaluation, it becomes less apparent what are you really doing.
It is not NIL, it is NULL.
They are one and the same. The == operator is a comparison operator. As a general trend, we use (object==NULL)

Is everything a function or expression or object in scala?

I am confused.
I thought everything is expression because the statement returns a value. But I also heard that everything is an object in scala.
What is it in reality? Why did scala choose to do it one way or the other? What does that mean to a scala developer?
I thought everything is expression because the statement returns a value.
There are things that don't have values, but for the most part, this is correct. That means that we can basically drop the distinction between "statement" and "expression" in Scala.
The term "returns a value" is not quite fitting, however. We say everything "evaluates" to a value.
But I also heard that everything is an object in scala.
That doesn't contradict the previous statement at all :) It just means that every possible value is an object (so every expression evaluates to an object). By the way, functions, as first-class citizens in Scala, are objects, too.
Why did scala choose to do it one way or the other?
It has to be noted that this is in fact a generalization of the Java way, where statements and expressions are distinct things and not everything is an object. You can translate every piece of Java code to Scala without a lot of adaptions, but not the other way round. So this design decision makes Scala is in fact more powerful in terms of conciseness and expressiveness.
What does that mean to a scala developer?
It means, for example, that:
You often don't need return, because you can just put the return value as the last expression in a method
You can exploit the fact that if and case are expressions to make your code shorter
An example would be:
def mymethod(x: Int) = if (x > 2) "yay!" else "too low!"
// ...
println(mymethod(10)) // => prints "yay!"
println(mymethod(0)) // => prints "too low!"
We can also assign the value of such a compound expression to a variable:
val str = value match {
case Some(x) => "Result: " + x
case None => "Error!"
}
The distinction here is that the assertion "everything is a expression" is being made about blocks of code, whereas "everything is an object" is being made about the values in your program.
Blocks of Code
In the Java language, there are both expressions and statements. That is, any "block" of code is either an expression or a statement;
//the if-else-block is a statement whilst (x == 4) is an expression
if (x == 4) {
foo();
}
else {
bar();
}
Expressions have a type; statements do not; statements are invoked purely for their side-effects.
In scala, every block of code is an expression; that is, it has a type:
if (x == 4) foo else bar //has the type lub of foo and bar
This is extremely important! I cannot stress this enough; it's one of the things which makes scala a pleasure to work with because I can assign a value to an expression.
val x = if (x == 4) foo else bar
Values
By value, I mean something that we might reference in the program:
int i = foo(); //i is a reference to a value
java.util.TimeUnit.SECONDS;
In Java, the i above is not an object - it is a primitive. Furthermore I can access the field SECONDS of TimeUnit, but TimeUnit is not an object either; it is a static (for want of a better phrase). In scala:
val j = 4
Map.empty
As far as the language is concerned, j is an object (and I may dispatch methods to it), as is Map - the module (or companion object) for the type scala.collection.immutable.Map.
Is everything a function or expression or object in scala?
None of it.
There are things that are not objects. e.g. classes, methods.
There are things that are not expressions. e.g. class Foo { } is a statement, and does not evaluate to any value. (This is basically the same point as above.)
There are things that are not functions. I don't need to mention any examples for this one as there would be plenty in sight in any Scala code.
In other words, "Everything is a X" is nothing more than a sales pitch (in case of Scala).

iPhone SDK: Please explain why "nil ==" is different than "== nil"

I have been programming iPhone SDK for around 6 months but am a bit confused about a couple of things...one of which I am asking here:
Why are the following considered different?
if (varOrObject == nil)
{
}
vs
if (nil == varOrObject)
{
}
Coming from a perl background this is confusing to me...
Can someone please explain why one of the two (the second) would be true whereas the first would not if the two routines are placed one after the other within code. varOrObject would not have changed between the two if statements.
There is no specific code this is happening in, just that I have read in a lot of places that the two statements are different, but not why.
Thanks in advance.
They are the same. What you have read is probably talking about if you mistakenly write == as =, the former will assign the value to the variable and the if condition will be false, while the latter would be a compile time error:
if (variable = nil) // assigns nil to variable, not an error.
if (nil = variable) // compile time error
The latter gives you the chance to correct the mistake at compile time.
They might be different if you are using Objective-C++ and you were overriding the '==' operator for the object.
They are exactly the same, it is just a style difference. One would never be true if the other is false.
if it's a recommendation that you use the latter, it's because the second is easier to catch if you accidentally type =. otherwise, they are identical and your book is wrong.
They can only be different if the "==" - Operator is overloaded.
Let's say someone redefines "==" for a list, so that the content of two lists is checked rather than the memory adress (like "equals() in Java). Now the same person could theoretically define that "emptyList == NULL".
Now (emptyList==NULL) would be true but (NULL==emptyList) would still be false.