Questions tagged [short-circuiting]
A feature of some languages to skip certain code at runtime that doesn't affect the outcome, especially when testing compound conditions
471
questions
1
vote
1
answer
31
views
using scalars with short-circuiting or
For a BMI calculator we need to create in programming class, I need to make sure that the values of size and weight are insinde of a certain range of numbers.
Every time the program tells me that I ...
0
votes
1
answer
17
views
why am i getting error when i m using short circuit to set default value for form input in react?
i'm creating form component to use the form in 2 different page and i want to check if is value is defind set it or give it a empty string ,but it doesn't work whem short circuit being used or ternary ...
-1
votes
2
answers
104
views
Order of evaluation between logical and assignment operators [duplicate]
I know that the order of evaluation and precedence of operators in C are independent. But I get confused when there are multiple operators that mandates the order of evaluation.
For example:
a = b &...
1
vote
1
answer
95
views
Checking Dictionary Key Existence in Golang on right side of boolean condition
I have an array of maps in golang, I'm iterating over the list and need to check if a key from the current iteration exists in the next map in the list, I know the normal way to check if an element ...
0
votes
0
answers
81
views
Return keyword inside the inline function in Scala
I've heard about to not use Return keyword in Scala, because it might change the flow of the program like;
// this will return only 2 because of return keyword
List(1, 2, 3).map(value => return ...
2
votes
1
answer
85
views
Weird streams behavior with sorted() and concat()
Stream evaluation is usually lazy (by default), unless statefull operations exist as part of the pipeline. I encountered a case where the lazyness is violated due to stateful operation and I don't ...
1
vote
2
answers
38
views
Short Circuit Evaluation with Components in Unity
I have a line of code: Rigidbody rigidbody = go.GetComponent<Rigidbody>() ? go.GetComponent<Rigidbody>() : go.AddComponent(typeof(Rigidbody)) as Rigidbody; where go is a GameObject. When I ...
0
votes
0
answers
12
views
Short Circuiting && interleaving: what if the statement already checked changes
I have a question about the processing of statements and short-circuit vs no short-circuit (I do not know the exact name for no short-circuit).
The scenario is the following.
Imagine I have two ...
0
votes
1
answer
37
views
Python: Unexpected behaviour of nonlocal variable in recursion
The following code is expected to set the nonlocal variable flag to true after 3 calls to recur(). I expect flag in the following code to be always true after recur(2) returns (starting from 0)
def f()...
2
votes
0
answers
106
views
Java stream short circuiting operations: Can we assume one by one processing?
The JavaDoc specifications about short circuiting operations only talk about infinite and finite streams and about the termination of these.
But I wonder if we can even safely assume that the elements ...
-1
votes
1
answer
28
views
Short-circuiting with helper function in print() [duplicate]
Can someone please explain why the following code comes out as "geeks" in the console?
def check():
return "geeks"
print(0 or check() or 1)
I'm assuming that Python ...
0
votes
0
answers
118
views
C++ What are the conditions of short circuit evaluation? [duplicate]
if (i - word.size() >= 0 && dp[i - word.size()] && s.substr(i - word.size(), word.size()) == word)
dp[i] = true;
i - word.size() >= 0 is the condition that I was using to ...
0
votes
1
answer
204
views
Enable submit button only when no error is found
I have a simple application in which I only want to enable the calculate button only when no-errors are found (an error is recorded if the value is not a number, or a value is less than 0). I perform ...
0
votes
1
answer
155
views
In Kotlin, how can I test and use a value without computing it twice?
Every so often, I find myself wanting to compute a value for some sort of filter operation, but then wanting to use that value when it's already disappeared into the condition-checking thing.
For ...
0
votes
0
answers
47
views
Short-Circuiting Interaction with Ternary Operator in JavaScript
I'm currently learning JavaScript and I encountered this problem:
const numArray = [1, 6, 9, 4, 21, 8, 15];
const sumEvenOdd = numArray.reduce((acc, current) =>
console.log(acc) && ...
1
vote
1
answer
642
views
Can I simplify a condition with short-circuit call chain in Dart?
Can this code snippet be simplified on the second line?
From:
GetBuilder<ProductController>(builder: (productController) {
return productController.reviewedProductList == null || ...
-1
votes
1
answer
269
views
How to group shorthand operators in shell script?
This shell script takes one -P optional option.
#!/bin/sh
usage() {
echo "Usage: $0 [-P path] URL [URL...]";
exit 0;
}
P='/default_path/'
getopts "P:" OPT &&...
1
vote
0
answers
34
views
What is the reason/benefit for writing short circuit conditional?
I was searching a lot about short circuit, but I have a big doubt with this code.
const getClient = (userInfoContext) => {
const context = userInfoContext && userInfoContext.get()
const ...
0
votes
1
answer
125
views
Python all short-circuiting with None element
I read everywhere that Python all and any functions support short-circuiting.
However:
a = None
all((a is not None, a + 1 > 2))
Throws the following error:
Traceback (most recent call last):
...
0
votes
1
answer
413
views
In Scheme, does `or` and `and` short circuit?
Do and and or short circuit in Scheme?
The following are two implementation of lat? (list of atoms). One uses cond … else and the other uses or and and. I was wondering if they are equivalent and the ...
1
vote
1
answer
231
views
Python 2 Syntax error when executing print in boolean expression
In order to demonstrate that python performs short-circuiting I tried to run the following code snipplet
True or print('here')
and expected the code to execute, evaluate to True and not print "...
-1
votes
3
answers
592
views
using Short-Circuiting ( || ) in Object in JavaScript
this block of code takes the values of the scored property and puts them in duplication object as a key and how many times the name got duplicated as a value using the || operator.
I understand that ...
6
votes
1
answer
215
views
How do I take an elementwise OR of several matrices in Julia?
I have a several boolean matrices, and I want a resulting matrix that indicates if any of the elements in that position of those matrices are true. Is there a single function in the Julia language ...
0
votes
1
answer
84
views
What's the AHK equivalent of one-line logical OR short-circuit evaluation?
For example, in JavaScript, the following code would log foo:
false || console.log('foo')
How to achieve the same logic in one line in AutoHotkey?
0
votes
1
answer
157
views
Terminate stream when value matches criteria, otherwise collect into a collection
I am using Java parallel streams for a chess engine. The stream is used to evaluate each chess Move in a given List of Moves. Each Move is mapped to an Integer representing the Move's value, then I ...
1
vote
0
answers
112
views
Logical and (&&) type of operator only for null types in Javascript
The logical && operator returns the left side iff it is evaluated as 'falsy'.
null && 10
> null
0 && 10
> 0
1 && 10
> 10
The nullish coalescing operator (...
0
votes
1
answer
500
views
One line if-condition-assignment in AutoHotkey
In JavaScript, we could use the following one-liner:
const condition = true
let foo
condition && (foo = 'foo') // 👈 one-liner
console.log(foo) // foo
I tried this in AHK:
condition := ...
6
votes
1
answer
306
views
Why does the second version of this run in exponential time?
I am writing a program to determine if the Levenshtein distance between two strings is exactly 2 in linear time.
I have an algorithm which does this. I use the naive recursive approach which scans ...
1
vote
2
answers
131
views
How to do short circuit print in C?
Hello everybody: I've an expression like this:
if (a == 1) {
printf("hello\n");
}
Is there a way to do something like that?
a== 1 && printf("hello\n");
It's called ...
2
votes
0
answers
22
views
Is function any() in pandas.groupby short-circuited? [duplicate]
While trying to answer another question, I noticed that function any(), when applied within groupby(), performs equally slow regardless of the content of the dataframe. For example, it takes the same ...
0
votes
2
answers
75
views
Short circuiting if statement
Say you have this nested if-statement:
int *x;
int y;
if (x == NULL || y > 5)
{
if (x != NULL)
// this should print if x != NULL and y > 5
printf("Hello!\n");
// this should ...
0
votes
3
answers
174
views
Prevent short-circuiting in Bash
I want to
generate a list of matching files
know if at least one of the patterns matched
The following will not work if there are any pdf files because then the first compgen will return true and ...
2
votes
3
answers
634
views
Short circuiting in place of ternary operator
Try to learn short circuiting and doing some assignments . Have the following code
game.odds.team1 < game.odds.team2 && `${game.team1} is more likely to win` || `${game.team2} is more ...
70
votes
3
answers
9k
views
Why does Python return [15] for [0xfor x in (1, 2, 3)]? [duplicate]
When running the following line:
>>> [0xfor x in (1, 2, 3)]
I expected Python to return an error.
Instead, the REPL returns:
[15]
What can possibly be the reason?
3
votes
0
answers
85
views
Python short circuit with a lambda expression raises syntax error
I wanted to return a lambda expression from a function if the argument to the function fulfills some criteria. I thought by writing something like the following this can be done:
def f(x=None):
...
3
votes
4
answers
168
views
() has the highest priority, why is it short-circuited?
() has the highest priority, why is it short-circuited?
int a = 1, b = 0;
(--a)&&(b++);
Why is (b++) still short-circuited?
-1
votes
1
answer
157
views
C++ Compilation Standard for “&” vs “&&” Expressions?
I have a core function evaluating 4+ simple arithmetic comparisons to return a bool. This will be called O(N^2) times in a very large loop, with a single conditional branch based on the return.
If the ...
2
votes
2
answers
351
views
Short circuiting in fold expressions
This is a self triggered question based on a self-answer I gave here.
This seems a pretty convincing explanation of why short-circuiting of logical operators is available in fold expressions, and of ...
1
vote
2
answers
256
views
Combining predicates in a functional way and allowing short-circuiting to work
Foreword
I asked a similar question: say I have a predicate auto p1 = [](int x){ return x > 2; } and a predicate auto p2 = [](int x){ return x < 6; }, how do I combine p1 and p2 to obtain p1and2 ...
0
votes
2
answers
917
views
Java 8 : Stream.filter not running as expected
Given:
List<String> str = Arrays.asList ("my", "pen", "is", "your", "pen");
Predicate<String> test = s -> {
int i = 0;
...
-1
votes
3
answers
93
views
A specific short-circuiting example in C
I understand the basic concept of short-circuiting with operators, but why does
int i = 0, j = -1, k = 1, m;
m = !(i++ && ++j) || ++k;
printf("%d %d %d %d", i, j, k, m);
have 1 -1 1 ...
1
vote
0
answers
25
views
Does the C language require short circuit/minimal evaluation of logical statements? [duplicate]
The GCC specification states that logical statements are short circuited: Logical Operators
Is this something specific to the GCC implementation or is short circuit logical evaluation inherently in C? ...
16
votes
2
answers
2k
views
Lazy function evaluation in any() / all()
Logical operators in Python are lazy. With the following definition:
def func(s):
print(s)
return True
calling the or operator
>>> func('s') or func('t')
's'
True
only evaluates the ...
0
votes
0
answers
293
views
How do airflow sql_sensors interpret skipped tasks from separate DAGs?
I am looking to utilize the ShortCircuit operator in DAG 1, so that it skips the DAG run if data is not available on a given day.
I have a DAG 2 which triggers DAG 1 and checks the status of ...
0
votes
1
answer
773
views
How to return nothing from an else block of an IF Condition in scala?
I am working on migrating a Java project to Scala and encountered the below code:
private void searchClauses( TCustomSqlStatement select ) {
if ( !searchInClauses.contains( select ) ) {
...
0
votes
2
answers
407
views
How to apply continue and yield multiple values from a for-loop in scala?
I am trying to convert a module of a java program into Scala. So far, I have been able to apply Scala's functional programming paradigm and its syntax in every module I converted. But I have come ...
76
votes
4
answers
6k
views
Does C# perform short circuit evaluation of if statements with await?
I believe that C# stops evaluating an if statement condition as soon as it is able to tell the outcome. So for example:
if ( (1 < 0) && check_something_else() )
// this will not be ...
1
vote
0
answers
90
views
OR short circuit in javascript not working as expected
The OR short-circuit is not working the way I think its supposed to. Ofcourse I am doing something wrong but can't figure it out. Please HELP! its driving me crazy
I am trying to solve the problem of ...
2
votes
1
answer
1k
views
Is map applied on all the list before filter findAny?
I want to filter a list for elements having a non null property and returning that property:
list.stream.map(a -> StringUtils.trimToEmpty(a.getProp())).filter( p -> StringUtils.isNotEmpty(p))....
4
votes
2
answers
312
views
Any/All python short-circuit: Why doesn't the following work? [duplicate]
Based on what I've seen on other stackoverflow pages:
Does Python's `all` function use short circuit evaluation?
Do all() and any() always short-circuit in order?
Is the shortcircuit behaviour of ...