Groovy NullObject should be null or not? - reflection

This example can be easily tested in the groovy console.
var a is evaluated to not null while b is evaluated to null.
Both are instances of org.codehaus.groovy.runtim.NullObject
def b = null
println b.getClass()
println b == null
def a = null.getClass().newInstance()
println a.getClass()
println a == null
Does anyone knows why?
This is a tricky thing when dealing with reflection code.

Actually I am wondering if this is not a bug. As an explanation... NullObject is a runtime/intermediate kind of Object. If you do anything on null, then NullObject is used. This, and the the implementation of NullObject#equals speaks for a==null returning true. It returns fails, because there is some internal code before that, that is for example determining if compareTo is called instead of equals and such things. Now this piece of code starts with
if (left == right) return true;
if (left == null || right == null) return false;
so null==null will return true, but NullObject==null will return false. On the other hand NullObject should not leak out if possible. Maybe we should fix newInstance() to return null.
I filled http://jira.codehaus.org/browse/GROOVY-5769 for this

In the equals method of NullObject, it only returns true if you are comparing it to null
As an instance of NullObject is not strictly null, it returns false...
Whether NullObject should return true if you call equals against another NullObject is probably a question best asked on the mailing list... I'll have a look and see if I can find any previous question.

Related

Weird behavior with Maps(A nullable expression can't be used as a condition)

Map<String,bool> map= { "key1":true, "key2":false };
/*
* Flags following compilation error:
* A nullable expression can't be used as a condition.
* Try checking that the value isn't 'null' before using it as a condition.
*/
if(map["key1"]) {
//do sth
}
/*So I try checking value isn't null as specified in error
*Still flags same compilation error
*/
if(map!=null && map["key1"]) {
//do sth
}
//This works
if(map["key1"] == true) {
//do sth
}
}
Based on the following snippet, may I know why both the 1st and 2nd if blocks fail but not the 3rd?
You misunderstood the error message.
A nullable expression can't be used as a condition.
means that you can't do:
bool? condition;
if (condition) {
...
}
Map<K, V>'s operator[] returns a V?. It returns a nullable type as a way of indicating failure when the key isn't found, and you need to check that the returned value isn't null, not that map itself is not null. For example:
if (map["key"] ?? false) {
...
}
Your third approach (which checks == true) works because it will perform a null == true equality check if the lookup returns null. However, you should prefer using ?? false since it conveys the intent better, and equality checks against true or false are usually a code smell.
The [] operator on Map can return null which makes it nullable which is explained in details here: https://dart.dev/null-safety/understanding-null-safety#the-map-index-operator-is-nullable
So your first example is invalid since null is not a bool. So you cannot directly use the value from the [] operator for a Map.
Your second example is invalid for the same reason since map["key1"] is bool?.
Third example works since null == true is always false. So it is fully valid to make a comparison which involves something which can be null.

returning result from binary search tree

I'm trying to determine if a value is found in the binary search tree.
If it's found, the value is printed. If not, a message is printed saying it wasn't found.
My problem is that even when the value is found, the message is printed saying that it wasn't found.
My result seems to reset even after returning True, and I am confused as to why this is happening... I think it's because I'm calling the function recursively, but I don't know how to fix this problem. Any help would be appreciated, thank you.
def lookUpVal(bst,val,result):
if bst == None:#base case, if the tree is 0, return none
return
elif bst['data'] == val:
print ("value found")
result = True
return result
lookUpVal(bst['left'],val,result)
lookUpVal(bst['right'],val,result)
def main(bst):
print ("Enter the value you want to find")
val = int(input())
result = 0
lookUpVal(bst,stud,result)
if result != True:
print ("Value not found")
The problem is with your result variable, you probably think you are passing by reference, what is actually happening is close to pass-by-value.
Here is an example:
def voo(x):
print('x:',id(x))
x = True
print('x:',id(x))
p = False
print('p:',id(p))
voo(p)
print('value of p:',p)
print('p:',id(p))
'id' returns a unique id for any object, including of course boolean ones.
Here's the output: (numbers will vary in your pc)
p: 1613433952
x: 1613433952
x: 1613433936
value of p: False
p: 1613433952
First note, False in output, p's value has not changed. But to see why that's happening, closely examine the id values, specially how x's id changed after assignment in function; which means python allocated a new object. And old one is still referenced by 'p', as evident in it's output, which has not changed.

Why does this R function not short-circuit properly?

I'm working my way through the Data Science courses at DataCamp. (Not a plug.) One of the practice lessons has the following completed solution:
# logs is available in your workspace
extract_info <- function(x, property = "success", include_all = TRUE) {
info <- c()
for (log in x) {
if (include_all || !log$success) {
info <- c(info, log[[property]])
}
}
return(info)
}
# Call extract_info() on logs, no additional arguments
extract_info(logs)
# Call extract_info() on logs, set include_all to FALSE
extract_info(logs, include_all = FALSE)
The first call (extract_info(logs)) works as I would expect it to: it returns a vector containing all the log entries (regardless of the value of log$success).
The second call (extract_info(logs, include_all = FALSE)) does not return the results I would expect. It returns a vector containing only those results where log$success evaluates to FALSE.
It seems to me that the use of the || operator should cause the if block to short-circuit, and the second call should return nothing. From what I can tell, R evaluates expressions from left to right; but this looks like it's evaluating from right to left.
Can someone explain what's going on here?
(According to the site, this is the correct solution, and there's nothing wrong with the code. I want to know why it works the way it does. Even if the answer is that I'm overlooking something painfully obvious and stupid.)
Well || is the "or" operator. You don't short circuit the "or" operator with a FALSE value; you basically ignore that parameter and just look at the next one because you are looking for any TRUE value.
Assume a is a boolean value. These should be equivalent (<==>).
# or
FALSE || a <==> a
TRUE || a <==> TRUE
# and
TRUE && a <==> a
FALSE && a <==> FALSE
It seems like this was a temporary confusion.
|| is OR and so if either condition evaluates to TRUE, the compound expression evaluates to TRUE. If include_all was TRUE, you could short-circuit the expression, but when include_all is FALSE, you must wait to see what the other part is.

how stacks are formed and value from a method return when the method has TWO recursive calls of itself from within itself

I have tried creating stacks for recursive inorder,preorder,postoreder traversal for binary tree and I was doing it pretty well. In other cases like, for example, for a test case my answer should be 'true',say.And, for example,
boolean method(root)
{
// more code
method(root.left());
method(root.right());
}
,somewhere,the call of method(root.left()) returns false and a call of method(root.right()) returns true that should be our answer. But since call of method(root.left() ) completes first and somewhere, in between it's execution, it might have returned false. then how do we get our result true from method(root.right())?? I think it is related to how stacks are formed and values from a method are returned when recursive calls ,in this way, happen.Explain it and correct me if I am wrong.
You need to return values. The method need to make use of the returned values in its logic to stop/continue the search.
You need to have that the base cases return either true of false. Then when doing the first recursive call you need only do the first if the result is true. The second recursive call would be the result of the method if it's needed. Thus you are looking at something like this:
boolean method(root)
{
if( root == null ) { // base case 1
return false;
}
if( root.value == someValue ) { // base case 2, what should be a positive
return true;
}
// default search left first and return true if true
if( method(root.left()) ) {
return true;
}
// default search right and return true if true
if( method(root.right()) ){
return true;
}
// return false since neither recursive calls were true
return false;
}
This is very verbose and can be written like this instead:
boolean method(root)
{
return root != null && ( root.value == someValue ||
method(root.left()) ||
method(root.right()));
}
I find the last more readable but novices might find the more verbose first one to be more clear.
In both the callee resumes operation after the first recursive call (which might have had it's share of calls as well) and continues it's logic and recurses on the right side if needed.
Don't care about the system stack. Care about the base case and test them. Then do the simplest of added complexity to do the default case so that you see the problem becoming smaller in the recursive call(s). It's much better going from simple to more complex than to try figuring this stuff out by starting at a large tree looking at whats happening with a very deep recursive round.

Simple question about operator ||

HEllo,
i try to do that in FlashBuilder (FlexProject)
protected function btn_detail_view_clickHandler(event:MouseEvent):void
{
CurrentState="Statistiques" || "PartMarche";
}
But it's not working, i guess this is not the right syntax but what's the right syntax ? Thanks
PS: i want to when the state is equal to "statistiques" or "partMarche" when i click on the button, that the current state changes to Detail view ;)
In ECMAScript languages, || is a short-circuit operator that will return the left-hand side expression result if it evaluates to a "truthy" value, or the right-hand side expression result otherwise. Non-empty strings always evaluate to truthy values, so the left-hand expression will always be returned here. The equivalent long-hand code to your example is:
if ("Statistiques")
CurrentState = "Statistiques";
else
CurrentState = "PartMarche";
This type of short circuit operator is used to set defaults to variables in certain situations:
CurrentState = PreviousState || "Some string";
In that example, if PreviousState is null or false or an empty string, CurrentState would be set to "Some string". If PreviousState is a string like "Some other string", CurrentState would be set to "Some other string".
Thanks for clarifying what you want to do. For checking what CurrentState is, you need to test it with an if condition:
if (CurrentState == "Statistiques" || CurrentState == "PartMarche")
{
// Of course, use the actual name of your detail view here
CurrentState = "DetailView";
}
Ok in fact i need to remove the .Statistiques to that code works in all the states
click.Statistiques="btn_detail_view_clickHandler(event)"
Sorry i just went too fast by myself instead of finishing the tutorial.
Your answers will prevent me to ask the next question ! thank you ;)

Resources