What is the difference between a return and a break in an infinite loop? - return

In doing the Guessing Game from the Rust Book (I won't put the link because it will probably not exist in a few weeks), there is a point where you use return to break out of the loop. I used break instead:
loop {
guess = guesser();
guess_cast = guess.trim().parse();
let guess_num = match guess_cast {
Ok(num) => num,
Err(_) => {
println!("Guess was not a number, try again");
continue;
},
};
if guess_num < answer {
println!("Too low");
} else if guess_num > answer {
println!("Too high");
} else {
println!("You guessed it!");
break;
}
}
Is there a real difference in using return over break in this case? What about other cases when you want to break out of an infinite loop?

If the loop is the final statement in the function, then there is patently no functional distinction between break; and return;. If this condition does not hold, there is evidently a difference, for return terminates execution of the function, while break only terminates execution of the loop.
In the case where they are functionally the same, which you use may vary based on context (which one feels better in this particular location), personal preference and what, if anything, you ate for breakfast.

Related

SwiftUI ViewBuilder: is it guaranteed that in `if/ese` statement `else` clause isn't executed when condition is true?

I ask this because I suddenly realized today that, since the if/else statement we use to build View in SwiftUI is interpreted by ViewBuilder, it may behave differently than the plain old if/else statement in Swift language. Could it be that, for some (e.g. performance) reason, SwiftUI pre-execute both clauses and cache the result? Does anyone know it for sure?
I remember I observed some confusing behavior in the past, which might be explained by this hypothesis. But unfortunately I can't recall an example.
The way a result builder transforms your code is spelled out in SE-0289: Result builders. Section “Selection statements” describes how if/else statements are transformed. It gives the following example:
Consider the following code:
if i == 0 {
"0"
} else if i == 1 {
"1"
} else {
generateFibTree(i)
}
Under this pattern, the example code becomes something like the
following:
let vMerged: PartialResult
if i == 0 {
var firstVar = "0"
var firstBlock = BuilderType.buildBlock(firstVar)
vMerged = BuilderType.buildEither(first: firstBlock)
} else if i == 1 {
var secondVar = "1"
var secondBlock = BuilderType.buildBlock(secondVar)
vMerged = BuilderType.buildEither(second:
BuilderType.buildEither(first: secondBlock))
} else {
var elseVar = generateFibTree(i)
var elseBlock = BuilderType.buildBlock(elseVar)
vMerged = BuilderType.buildEither(second:
BuilderType.buildEither(second: elseBlock))
}
You can also read a detailed description of the transformation algorithm, but I think the example makes it clear enough that it will only execute one branch of an if/else statement.

Control Statement Violation inside for-loop

I am using SwiftLint in my app. I am getting Control Statement Violation: if, for, guard, switch, while, and catch statements shouldn't unnecessarily wrap their conditionals or arguments in parentheses. (control_statement).
What is wrong with that code? Why i am getting that waring?
Thanks in Advance
for i in 0..<images.count {
if(i == images.endIndex - 1) {
print(i)
}
}
Its simply telling parentheses start ( and parentheses end ) symbols are now not necessary to provide in control statement' conditions so your code will go without () in control statement conditions for example your code will look like below
for i in 0..<images.count {
if i == images.endIndex - 1 {
print(i)
}
}
You have added parentheses in if condition.
Remove it.
for i in 0..<images.count {
if i == images.endIndex - 1 {
print(i)
}
}
You can check detail rule here.

Is it possible to define your own operators in Rascal?

I'm writing some test helper functions to make the output more sensible:
bool tstEq(first, second) {
if(first == second)
return true;
else {
println("<first> was not equal to <second>");
return false;
}
}
Is it possible to do something like this?
bool ===(first, second) = tstEq(first, second);
usage:
test bool myTest() = 1 === 2
Which would result in something like:
rascal>:test
1 was not equal to 2
bool: false
A short answer: no. I fully agree that this can be convenient (but may also lead to less readable code).
Given the large list of topics we want to address first, it is unlike that such a feature will come to Rascal in the near future.

Is there a language where we can mark value as result and then continue function/method body?

I was reading smalltalk tutorial and this idea came to my mind.
Assume we have some language and there instead of return we're marking some value as final return value and then we continue method, once method end is reached - no matter what else was called we're returning marked value unless something else specified manually like this:
Let's say ^^ is a operator that marks value for return if no explicit return is found till end of method
m1()
{
^^1;
some_other_code;
}
m2(par)
{
^^2;
if par == 1: return 1;
some code;
}
m3(par)
{
if par == 1: return 1;
else if par == 0: ^^0;
do some stuff;
if par < 0: return -1;
}
m1() should return 1
m2(0) should return 2
m2(1) should return 1
m3(0) should return 0
m3(1) should return 1
m3(-2) should return -1
This is a little similar to ruby's tap() but not the same
Pascal did that. The return value was set by assigning to the function name. Swift does something not quite the same: You can mark code anywhere that will be executed when the function exits. Your return statement exists, but only after other code written somewhere else gets performed.

How to mute jslint error on do{}while(false)

In this simple code:
do {
console.log('o');
} while (false);
jslint produces a warning on the last line saying Unexpected 'false'
I understand why, but I still want to mute it because in these cases that's how I want to have the control flow.
Let's look at what jslint expects in the while statement. From the source:
labeled_stmt('while', function () {
one_space();
var paren = next_token;
funct.loopage += 1;
advance('(');
step_in('control');
no_space();
edge();
this.arity = 'statement';
this.first = expected_relation(expression(0));
if (this.first.id !== 'true') {
expected_condition(this.first, 'unexpected_a');
}
no_space();
step_out(')', paren);
one_space();
this.block = block('while');
if (this.block.disrupt) {
prev_token.warn('strange_loop');
}
funct.loopage -= 1;
return this;
});
It mostly reads like English. 'while', one space, (, no space, expected expression, no space, ).
So let's look at what an expression(0) is. You can read through the source if you're really interested, but to be honest I can't really wrap my head around it either. Sorry. https://github.com/douglascrockford/JSLint/blob/master/jslint.js
As far as I can tell, though, expression(0) traverses the tree of operators and operands, and looks for values with a Right Binding Power greater than 0? And false has a binding power of 0? But variables and comparisons are okay here. I have no clue how that even works. Ask Crockford.
As for shutting up jslint, here is my suggestion:
/*jslint devel: true, continue: true */
var i = 0;
var forever = false;
do {
i = i + 1;
if (i < 5) {
continue;
}
console.log('o');
} while (forever);

Resources