What's the word for a boolean and statement stopping if the first returns false? - boolean

Sorry the title isn't descriptive, but if I could describe it well I probably would've found my answer.
In Python, if you were to run the following:
def fun1():
print("fun1 runs")
return False
def fun2():
print("fun2 runs")
return True
x = fun1() and fun2()
It would print the statement
fun1 runs
because after fun1 returns False, x will be false regardless of what fun2 is so fun2 never runs.
What's the word for this? I ask because I wanted to search if PHP boolean expressions do the same thing but didn't know what it was called.
Sorry for asking a silly question about terminology, but it's been bugging me!

if I got you right then you are talking about short-circuit evaluation

Related

Try-Catch Macro in Julia

I have the following functions.
foo(x) = x + 1
bar(x) = x * 2
I use them in a wrapper function (not sure whether this is even important).
function baz(x)
d = Dict{Symbol,Any}()
d[:foo] = foo(x)
d[:bar] = bar(x)
return d
end
The problem is that foo() and bar() can fail, and I want the code to continue running in this case. Introducing try catch statements would make the code very messy, however. So, is there maybe one of the following two solutions out there, that could make this easier?
Dream Solution
A macro that I could just write in front of d[:foo] = foo(x) and which in case of failure would write a default value do d[:foo].
Also-a Solution
A macro that would just continue if the code fails.
So, I managed to do the following. However, I have no clue if this is in any way good style.
macro tc(ex)
quote
try
$(esc(ex))
catch
missing
end
end
end
#tc foo(1)
1
#tc foo("a")
missing
Note the $(esc(ex)). This is important. If the expression is not escaped, the macro will work as expected in the global scope but not inside a function (as in the question). If anyone can provide a crisp explanation of why this is the case, please add a comment.

Swift - understanding return types in recursion: when should return the function vs. just return on its own

This may be a little too general for this forum, but hoping someone can explain this in a way that makes sense to my brain. I've tried reading and researching and have found lots of examples - but I still don't understand the "why" which means that I am not understanding exactly how a program comes back from a function return.
Here is a very simple function I wrote that solves a puzzle using backwards recursion. It works well.
func solver(grid: [[Int]])->[[Int]] {
var returnGrid = constraintPropogation(grid: grid)
if contradictionCheck(grid: returnGrid) == false {
return returnGrid
} else {
if returnGrid.flatMap({$0}).filter({$0 == 3}).count == 0 {
print("SOLVED**********")
gridPrint(grid: returnGrid)
print()
stopFlag = true
stopAnswer = returnGrid
return returnGrid
} else {
let randStart = getRandomStart(grid: returnGrid)
returnGrid[randStart.x][randStart.y] = 0
solver(grid: returnGrid)
returnGrid[randStart.x][randStart.y] = 1
solver(grid: returnGrid)
}
}
if stopFlag == true {return stopAnswer}
return solver(grid: returnGrid)
}
My issue is understanding the returns. In the third line of the function if a contradiction check fails this means that we've gone down a path that would not be possible. Therefore we return. That makes sense. The second return in the middle of the function occurs when the puzzle is solved, so it makes sense to return there. But the last one at the end "return solver(grid: returnGrid)" is challenging to my understanding. Here we are returning but also calling this same function again. This is not going deeper into the potential solution path (that happens in the "else" section where the function is called). Why do we need to call the function again rather than just returning? What is happening under the hood? Does the return happen first where we "pop back up a level" and then we are calling the function again effectively one rung higher on the stack? When I write these words I realize that I have a vague understanding - but somehow it is not all clicking together for me.
Am at the point now that when I'm writing functions that involve recursion I just try both returning on own or returning and calling function again to see which one achieves what I want. But I'd really like to understand it rather than just guessing. If anyone had a simple explanation I would appreciate it.
Your function solver takes an array of arrays, and returns an array of arrays. Any call to return(something) returns that something to the caller.
Saying return(someArrayOfArrays) means you are done, and have a result.
Saying return(solver(someArrayOfArrays)) says "call this function again, passing in a new value. Return whatever the result is as the function result." The current call to solver() is done doing work, and passes its intermediate results to another call to the function. That's the recursion. You can think of this as nesting a function call inside a function call inside a function call, or stacking function calls on top of each other.
The call to solver(grid: returnGrid) does not make any sense. That is a recursive call, but you ignore the result. Thus, that call does nothing useful. If your remove that line, it won't make any difference to the outcome. That line is saying "Go do a bunch of work and find an answer for me, but I will throw away your answer". The compiler should give you a "function result ignored" warning at that line.
Beyond that, I can't tell what your code is doing. It appears to be modifying at least one global variable, "stopAnswer". That suggests it's not a pure recursive function.

swift when should return have parenthesis and when does it not matter?

Is there ever a case where "return n" will cause a problem due to something within ". . ." ?
func foo() -> Int
{
. . .
return n
}
Or, should I always use return( n ) ?
func foo() -> Int
{
. . .
return( n)
}
UPDATE...
The main reason for this question is trouble I once had in viewDidLoad() where the final instruction line was simply "return" because I didn't believe () were needed. However, I had several lines below, which got executed.
(I had temporarily inserted the line with just "return" while debugging.)
This caused confusion and took a while to debug.
From then on, my policy was to always use return( . . . ) and never saw the problem again.
Someone on StackO explained this Swift behavior, but I don't remember the explanation.
I don't think the parentheses are needed unless you declare your function to return a tuple.
As gnasher says in their answer, the parens in the return are weird.
I seem to remember that a function result in Swift is always considered to be a tuple, where Void is a special case empty tuple. If my (vague) memory is correct that might explain why the parens are valid. I need to see if I can dig that up.
The parentheses are absolutely weird. They are weird in C, in Swift they are bizarre.
And since space is relevant in Swift, your weird spacing makes it even weirder.
As a rule, you don’t write anything unnecessary in Swift.
Here is answer to my question:
Parens are only needed if line with "return" is between lines of code
in same func. Other than that case, as far as I know, parens after
return are superfluous.
Here is my test for proving this............
With this code (no parens after return)...
print("viewDidLoad Abort.")
return
print("viewDidLoad WTF!")
...I get:
viewDidLoad Abort.
viewDidLoad WTF!
But, with this code (parens after return)...
print("viewDidLoad Abort.")
return()
print("viewDidLoad WTF!")
...I only get:
viewDidLoad Abort.
Thus, in response to all the esteemed advice above, I shall not use parens after return, unless temporarily aborting a func by using "return()" unless there is a better way to temporarily abort func.

Is a while loop already implemented with pass-by-name parameters? : Scala

The Scala Tour Of Scala docs explain pass-by-name parameters using a whileLoop function as an example.
def whileLoop(condition: => Boolean)(body: => Unit): Unit =
if (condition) {
body
whileLoop(condition)(body)
}
var i = 2
whileLoop (i > 0) {
println(i)
i -= 1
} // prints 2 1
The section explains that if the condition is not met then the body is not evaluated, thus improving performance by not evaluating a body of code that isn't being used.
Does Scala's implementation of while already use pass-by-name parameters?
If there's a reason or specific cases where it's not possible for the implementation to use pass-by-name parameters, please explain to me, I haven't been able to find any information on it so far.
EDIT: As per Valy Dia's (https://stackoverflow.com/users/5826349/valy-dia) answer, I would like to add another question...
Would a method implementation of the while statement perform better than the statement itself if it's possible not to evaluate the body at all for certain cases? If so, why use the while statement at all?
I will try to test this, but I'm new to Scala so it might take me some time. If someone would like to explain, that would be great.
Cheers!
The while statement is not a method, so the terminology by-name parameter is not really relevant... Having said so the while statement has the following structure:
while(condition){
body
}
where the condition is repeatedly evaluated and the body is evaluated only upon the condition being verified, as show this small examples:
scala> while(false){ throw new Exception("Boom") }
// Does nothing
scala> while(true){ throw new Exception("Boom") }
// java.lang.Exception: Boom
scala> while(throw new Exception("boom")){ println("hello") }
// java.lang.Exception: Boom
Would a method implementation of the while statement perform better than the statement itself if it's possible not to evaluate the body at all for certain cases?
No. The built-in while also does not evaluate the body at all unless it has to, and it is going to compile to much more efficient code (because it does not need to introduce the "thunks"/closures/lambdas/anonymous functions that are used to implement "pass-by-name" under the hood).
The example in the book was just showing how you could implement it with functions if there was no built-in while statement.
I assumed that they were also inferring that the while statement's body will be evaluated whether or not the condition was met
No, that would make the built-in while totally useless. That is not what they were driving at. They wanted to say that you can do this kind of thing with "call-by-name" (as opposed to "call-by-value", not as opposed to what the while loop does -- because the latter also works like that).
The main takeaway is that you can build something that looks like a control structure in Scala, because you have syntactic sugar like "call-by-name" and "last argument group taking a function can be called with a block".

What does colon do in a php function boolean parameter do?

It's a newbie question I suppose but please explain what this code states with the ":"
switchURL(changeUrl: boolean = false){
if (changeUrl){
location.goTo(..............)
}
}
This function is called without parameters - switchURL(). My misunderstanding is bigger having in mind that the if statement works as changeURL is true.
Thank you in advance!
Regardless of the programming language, your code seems to be defining a function.
switchURL(changeUrl: boolean = false) {…}
If this syntax is correct (I don't know), its expected meaning would be that switchURL accepts an argument called changeUrl of type boolean and its default value will be false.
So, if you call switchURL() without any arguments, the location.goTo(…) code won't be executed because the argument (and therefore the condition) will be false.