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
456
questions
0
votes
0
answers
39
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) && ...
0
votes
1
answer
44
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
38
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
31
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
0
answers
6
views
Isolation of two 3-phase Auto transformers
I'm making a H-bridge using 20N60 Power MOSFET.
The input to the first pair of MOSFET is 300V DC and second pair of MOSFET is 160V DC. The high power DC is obtained from a 3-phase rectifier with the ...
0
votes
1
answer
36
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
104
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
88
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
136
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
116
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
46
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
0
answers
16
views
Shortcircuit evaluation confusion
I've got a question related to the shortcircuit evaluation. Here's the code:
function updateRecords(records, id, prop, value) { if (value === '')
{
delete records[id][prop]; } else if (prop ...
0
votes
1
answer
26
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
41
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
155
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 := ...
7
votes
1
answer
289
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
103
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
63
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
96
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
4
answers
235
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 ...
68
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
46
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
156
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
106
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
128
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
121
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
373
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
89
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? ...
12
votes
1
answer
975
views
Python: 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'
only evaluates the ...
0
votes
0
answers
141
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
270
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
242
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
5k
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
61
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
464
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
144
views
Any/All python short-circuit: Why doesn't the following work?
Based on what I've seen on other stackoverflow pages:
Does all(list) use short circuit evaluation?
Do all() and any() always short-circuit in order?
Is the shortcircuit behaviour of Python's any/...
0
votes
2
answers
64
views
Timing the shortcircuit in Python gives unexpected results
import time as dt
success = True
can_test = True
time = 0
for i in range(10000000):
start = dt.time()
if success and can_test:
stop = dt.time()
time+= stop-start
print(f'"and&...
1
vote
0
answers
51
views
Do lifted operators on nullable value types employ short-circuiting?
I wonder whether code like this should execute GetAnotherValue()?
int? x1 = null;
var check = x1 <= GetAnotherValue();
I assume it shouldn't since that sounds more reasonable to me. But I'm not ...
0
votes
1
answer
87
views
Implement "return" of sequential languages in Haskell
Currently reading through the Learn You a Haskell, and I've come across this example for searching if a sublist is inside a list:
searchSublist :: (Eq a) => [a] -> [a] -> Bool
searchSublist ...
2
votes
1
answer
1k
views
Rust: How to short-circuit exit from a chain of iterator methods on first Err or None?
Consider a chain of iterator methods:
.iter().a().b().c()
where a produces values of type Option (or Result). Is there a way to have the whole chain return None (or (Err(_)) as soon as a yields a ...
8
votes
5
answers
927
views
Short circuit and operator precedence in C
I know that logical operators in C follow short circuiting but my doubt is that are short circuiting and operator precedence rules not opposing each other. See the below example :
#include<stdio.h&...
1
vote
2
answers
2k
views
Using logical operators on integers in C
Logical OR and Logical AND operator on integers in C
Can you explain me why the values of a,b,c are 11,10,1 respectively.
Why the value of b remains same as 10?
#include <stdio.h>
int main()
{
...
0
votes
1
answer
384
views
Question about short circuiting with python logical operators
According to short circuit rules, any time we have a True or ... statement it returns True, regardless of the rest of the statement. e.g., even if the rest of the statement throws an error, it would ...
0
votes
1
answer
67
views
Will SQL Server be smart enough to not execute expensive queries if it is not needed ? (short-circuiting)
So SQL Server does not have short-circuiting in the explicit manner as with for example if-statements in general-purpose programming languages.
So consider the following mock-up query:
SELECT * FROM ...
1
vote
1
answer
56
views
Will Using Short-Circuiting in WHERE Clause Improve Speed
Use case: I am going to be using SQL Server to retrieve values from a large table (1,000,000+ rows) where many different columns can be used as filter criteria, some more frequently used than others.
...
3
votes
1
answer
230
views
Can someone explain me why "operator precedence" applies to logical operators like "||", "&&" in javaScript
Can someone explain me why operator precedence applies to logical operators like || and && in JavaScript? What does that mean in an operation like:
true || false && false
the false &...
0
votes
1
answer
21
views
Is it possible for a DNS LoadBalancer RoundRobbin to do Graceful degradation?
I need to setup a LoadBalancing DNS entry, so a classic round robbin mechanism, given the following diagram:
________________
| |
...
0
votes
2
answers
58
views
forEach returning undefined when comparing option values and returning parent id
So I want to grab all the <select> elements and grab the ID of a "country" drop down.
I have the following, which pushes the <selects> into a HTMLcollection then compares the first ...