how to restrict the print values inside groovy each closure? - collections

in groovy loop like :
x = [1,2,3,4,5]
x.each { i ->
// other CRUD type functionality - required
// print each values - not required
}
Can I restrict the print values inside the each clause. Actually I want the CRUD functionality to execute. But after that print i prints each values which I don't want.
my output as of now :
1
2
3
4
5
6
==>1
==>2
==>3
==>4
==>5
==>6

Or, use findAll to just then work on a list of interest:
[1,2,3,4,5].findAll { it % 2 == 0 }.each { println it }
Will just print the even numbers for example
Edit
Hang on, do you mean in the groovy console where it shows you the return value of the script in inverse type?
each returns the list it worked on, so you'll see the list after execution.
You can stop this by putting null at the end of your script (or something that returns null such as println "done")

Use a return statement in the end of the script.
x = [1,2,3,4,5]
x.each{println it}
return

Return from the closure to skip elements:
def list = [1, 2, 3, 4, 5, 6]
list.each { i ->
// skip uneven values
if (!(i % 2 == 0)) return
println i
}
Not that the return just skips the iteration step and does not return from the function the code is executed in.

Related

Kusto: Handling null parameter in user defined funtion

I am writing a custom User defined function in kusto where I want to have some optional parameters to the function which will be used in the "where" clause. I want to dynamically handle this. For example: If the value is present, then my where clause should consider that column filter, else it should not be included in the "where" clause>
Eg (psuedo code where value is not null):
function Calculate(string:test)
{
T | where test == test | order by timestamp
}
Eg (psuedo code where value is null or empty. My final query should look like this):
function Calculate(string:test)
{
T | order by timestamp
}
What is the efficient way to implement this. I will call this function from my c# class.
you can define a function with a default value for its argument, and use the logical or operator and the isempty() function to implement the condition you've described.
for example:
(note: the following is demonstrated using a let statement, but can be applied similarly to stored functions)
let T = range x from 1 to 5 step 1 | project x = tostring(x)
;
let F = (_x: string = "") {
T
| where isempty(_x) or _x == x
| order by x desc
}
;
F("abc")
if you run F() or F("") (i.e. no argument, or an empty string as the argument) - it will return all values 1-5.
if you run F("3") - it will return a single record with the value 3.
if you run F("abc") - it will return no records.

How does null move up the call stack in recursive functions, if a return value of null is not specified?

Hi I'm currently learning about recursive Inorder Binary Tree Traversal using C#. There's one main aspect I cannot understand, in particular with this code below.
public void InOrder(BinaryTreeNode node)
{
if (node != null)
{
InOrder(node.Left);
Console.WriteLine(node.Value);
InOrder(node.Right);
}
}
If I had a Binary tree that looked like this...
9
/ \
4 20
/ \ / \
1 6 15 170
I know that eventually by recursively calling Inorder(node.left) I will get to the left leaf of the binary tree i.e. the very end of the tree, where node.left will equal null as there are no more nodes.
The tree would look like this...
9
/ \
4 20
/ \ / \
1 6 15 170
/
null
Because node.left = null, the first recursive function
InOrder(node.left)
will terminate, and
Console.Writeline(node.left)
will execute
Printing a value of 1
Eventually these null values move up the call stack after each node is analysed, and all nodes are printed, the tree starts to look like this, as null value moves up the tree..
9
/ \
4 20
/ \ / \
null 6 15 170
/ \ / \
null null null
Eventually all the nodes in the tree are equal to null, and all nodes are printed in order to an output of ...
1, 4, 6, 9, 15, 20, 170
What I don't understand is how this null value is moving up the tree, and changing all the nodes that have been analysed to null when there is no return value. Normally there would be a base case like...
if (node == null)
{
return null;
}
For this, I understand that null is being returned so will persist/return up the call stack. But for fist block of code above, there is no return statement.
I also find it just as confusing when there is only a return statement without a return value like...
if (node == null)
{
return;
}
Again there is no return of null specified, so how does this null value move up the tree as each node is evaluated?
There isn't a problem with any of this code, it works as expected, and prints all the nodes of the Binary Tree InOrder. This is more about understanding Recursion, and why the first block of code still works even though a return null value is not specified.
Thanks in Advance for the help.
there is no return of null specified, so how does this null value move up the tree as each node is evaluated?
The function will still return, even if there is no value to return. It's done executing, so control is passed back to the caller.
if (node != null) <- skipped entirely when the node is null
{
InOrder(node.Left);
Console.WriteLine(node.Value);
InOrder(node.Right);
}
For the tree you gave, this is what happens at the node with value=1:
It's not null, so we go into the if block.
We evaluate InOrder(node.Left) which is just InOrder(null):
It's null, so the if block is skipped.
We return to the caller, InOrder(node with value=1)
Console.WriteLine(node.Value) prints 1.
etc...
Although you can't 'see' the base case in the code, it's still there :) just implicitly.

How does recursion work its way back?

I'm working to understand recursion more in depth and I'm struggling with WHY it works the way it does. I know that this function returns the square of the previous return (2, 4, 16, 256, etc.), but I'm wonder how it gets the answer.
My understanding of recursion is that it iterates back down to the base case, but that leads me to believe that it would eventually always return the base case. How does it work its way back up to returning something new every time?
int p1a(int num) {
if (num == 1) { return 2; }
else {
return pow(p1a(num-1), 2);
}
}
Here's an example of my thinking
num = 3
passes through the base case and hits pow(p1a(num-1), 2)
moves back to the start
again passes through the base case and hits pow(p1a(num-1), 2)
at this point, num = 1, so it would return 2
How is it working its way back up to return 16? I understand what the function returns, but I'm stuck on the process of getting there.
You're thinking about the steps linearly, while the execution is actually nested (represented by indenting):
call p1a(3)
call p1a(2)
call p1a(1)
return 2
return pow(2, 2)
return pow(4, 2)
So the final return returns the value 16.

Not Sure If My Function Is Classified As Recursive

I have some pseudocode here:
index = 0
function search(A, n)
if A[index] == n
return true
else
index += 1
return search(A, n)
print search ( [0, 1, 2, 3, 4 … 99], 5 )
Is this function recursive even with the index variable? I know that I'm calling the method inside of itself (which is recursion) but I don't know if proper recursion is allowed to have incrementing variables outside the function.
Yes. A recursive function is one that calls itself (or may do). Nothing else it does or does not do is relevant to that definition. "Does" is to be interpreted in the sense of code or potentiality, not in the sense of what actually happens on any given run.
On the other hand, there are plenty of things that it are unwise for a recursive function to do, and depending on a global variable to control its operation is one of them.
suggest you to put it in this way:
function search(A, n)
function aux(i)
if A[i] == n
return true
else
return aux(i+1)
return aux(0)
it's tail recursive.

How can I determine end-of-cursor in Rust using sqlite3 Select?

I'm just starting to evaluate Rust. Using Rust and the sqlite3 repo on Github, I'm attempting to determine EOF for a Cursor. I'm not sure how to do that "correctly", I think it may be via the "match" statement.
The 2nd line in the following 2 lines is how I'm currently determining EOF, but this is obviously not the "correct" way:
let oNextResult:sqlite::types::ResultCode = oDbCursor.step();
tDone = (fmt!("%?", oNextResult) == ~"SQLITE_DONE");
The following is the unfinished function containing the above 2 lines. Please excuse the lack of Rust naming-convention, but I will look at implementing that.
/********************
**** Update Data ****
*********************/
fn fUpdateData(oDb1:&sqlite::database::Database, iUpdateMax:int) -> bool {
println(fmt!("Updating %d Rows .......", iUpdateMax));
let sSql:~str = fmt!("Select ikey, sname, iborn, dbal from test LIMIT %d",
iUpdateMax);
let oDbExec = oDb1.exec(sSql);
if oDbExec.is_err() {
println(fmt!("Select Failed! : %?, sql=%s", oDbExec, sSql));
return false;
}
println("Select succeeded. Processing select list .....");
let mut iUpdateCount: int = 0;
let oDbCursor:sqlite::cursor::Cursor = oDb1.prepare(sSql, &None).unwrap();
let mut tDone:bool = false;
while !tDone {
let oNextResult:sqlite::types::ResultCode = oDbCursor.step();
tDone = (fmt!("%?", oNextResult) == ~"SQLITE_DONE");
if !tDone {
let sKey = oDbCursor.get_text(0);
let sName = oDbCursor.get_text(1);
let sBorn = oDbCursor.get_text(2);
let sBal = oDbCursor.get_text(3);
println(fmt!("skey = %s, sname = %s, sBorn = %s, sBal = %s", sKey,
sName, sBorn, sBal));
iUpdateCount += 1;
}
}
println(fmt!("Update succeeded, items updated = %d", iUpdateCount));
return true;
}
I don't know if there is a correct way at the moment but you can also the result codes from the types module:
use sqlite::types::ResultCode;
and then do something like this so there's no need for using fmt!
while cursor.step() == SQLITE_ROW {...}
or this:
while cursor.get_column_count() != 0 {...; cursor.step()}
Function get_column_count returns an int. If there's no data it will return 0. It calls int sqlite3_data_count(sqlite3_stmt *pStmt); under the hood and here's what sqlite docs say about it:
The sqlite3_data_count(P) interface returns the number of columns in
the current row of the result set of prepared statement P. If prepared
statement P does not have results ready to return (via calls to the
sqlite3_column_*() of interfaces) then sqlite3_data_count(P) returns
0. The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. The sqlite3_data_count(P) routine returns 0 if the previous
call to sqlite3_step(P) returned SQLITE_DONE. The
sqlite3_data_count(P) will return non-zero if previous call to
sqlite3_step(P) returned SQLITE_ROW, except in the case of the PRAGMA
incremental_vacuum where it always returns zero since each step of
that multi-step pragma returns 0 columns of data.
As it's mentioned on the readme file rustsqlite interface is not finalized, watch out for changes.

Resources