Is there a language that breaks out of conditional statements as soon as they become false? - programming-languages

I thought that I had come across this before, but I can't remember when or what language it was.
Basically if I have the following in C#:
someCondition = true
if(someCondition)
{
// Do Something
if(anotherCond) {
someCondition = false;
continue;
}
// Do Something Else
}
In C# this will break out of the body of the if statement when someCondition changes, meaning that //DO Something Else only gets processed if someCondition doesn't change...
Is there a language that will do the interior if statement checking/continue automatically i.e. be able to write:
someCondition = true
if(someCondition)
{
// Do Something
if(anotherCond){
someCondition = false;
}
// Do Something Else
}
with the same behaviors as the previous? Obviously there are multiple ways to get this behavior in every language conceivable, what I am interested in is if there is a language that by design has this functionality.
Edit: Reduced the examples so hopefully people can see what is happening, when someCondition changes (i.e. the condition that the if statement relied on to begin, we should break out of the remaining if statement. I am not looking for a way to do this in C#, or any particular language, but for a language that does this automatically.

You can create a property in C# that throws an exception on any condition you set, aka truth=true. The exception will break out of the loop to wherever you have your catch.
An example in C#:
public class MyException : Exception { }
public bool truth
{
get { return _truth; }
set
{
_truth = value;
if(value)
throw new MyException();
}
}
bool _truth;

I think you can simulate what you want in C# like so:
void ExecuteWhile( Func<bool> condition,
IEnumerable<Action> executeWhileTrue,
IEnumerable<Action> executeWhileFalse)
{
if (condition())
{
foreach (Action action in executeWhileTrue)
{
action();
if (!condition())
return;
}
}
else
{
foreach (Action action in executeWhileFalse)
{
action();
if (condition())
return;
}
}
}
and then use it as such:
truth = true;
while (true) // loop forever
{
ExecuteWhile( () => truth,
new List<Action> { () => { /* do something that might set truth to false*/},
() => { /* do something else*/}},
new List<Action> { () => { /* do something that might set truth to true*/},
() => { /* do something else*/}});
}
And to answer your question: no, I don't think there is a language with this as a build-in feature.

As far as I understood, the following is wanted:
if (cond) {
A;
B;
C;
}
shall behave as if written thus:
if (cond) {
A;
if (cond) {
B;
if (cond) {
C
}
}
}
IMHO, this would be a silly feature, unlikely to be implemented in any language except maybe in INTERCAL.
Why do I think that?
Well, suppose someone wants to refactor the code and moves B;C to a subroutine.
if (cond) {
A;
BC();
}
subroutine BC() { B;C }
The block - according to our feature - will mean as before:
if (cond) {
A;
if (cond) BC();
}
But what about our subroutine? The language designer has 2 choices here:
Treat the call BC() as atomic, i.e. in the subroutine, the
condition cond is not checked before statement C. This would mean
such a simple refactoring would change the meaning of the program
drastically.
Somehow pass the information that every statement must be guarded
with cond to the subroutine so that the behaviour of our block remains
unchanged. This, of course, leads to the silly situation that the
behaviour of any subroutine would depend upon the context it was
called in. A subroutine with n atomic statements would have n possible ways to behave even if it had no arguments and would not use non local mutable state explicitely, depending on how many of the statements would be actually executed. (Note that nowadays the trend is to minimize the most often harmful effects of shared non-local state. OO languages do it with encapsulation, FP languages by banning mutable state altogether.)
In any case, no matter how the language designer decides, we would have a feature that is the direct contradiction of the principle of the least surprise. It is clear that programs in such a language would be utterly hard to maintain.

If you broke you big bunch if/else statements into succinct little methods which tested each little piece of the puzzle, you could rely on the compilers short circuit boolean evaluation
I'm not sure if that helps as your example is a big vague. You don't say if you're doing any processing or if it's just a bunch of checks. Either way, breaking your code into smaller methods may help you out.

You can use a do..while loop:
do
{
} while (truth == true);
thats if i've understood correctly!

You say while true... but while what is true. I would think your loop will run infinitely regardless of the language used. Assuming true will be a real condition... I would say just set the exit condition in one of the if blocks. You question is a bit hard to understand. Also the continue is unnecessary.

Related

Should the variable value be checked before assigning?

I know this might sound like a silly question but I'm curious should I check my variable value before assigning?
like for example if I'm flipping my skin (Node2D composed of sprite & raycast) based on direction (Vector2) :
func _process(delta):
...
if(direction.x>0):
skin.scale.x=1
elif(direction.x<0):
skin.scale.x=-1
#OR
if(direction.x>0):
if(skin.scale.x!=1):
skin.scale.x=1
elif(direction.x<0):
if(skin.scale.x!=-1):
skin.scale.x=-1
would the skin scale be altered every _process hence consuming more CPU usage
OR
if the value is same will it be ignored?
First of all, given that this is GDScript, so the number of lines will be a performance factor.
We will look at the C++ side…
But before that… Be aware that GDScript does some trickery with properties.
When you say skin.scale Godot will call get_scale on the skin object, which returns a Vector2. And Vector2 is a value type. That Vector2 is not the scale that the object has, but a copy, an snapshot of the value. So, in virtually any other language skin.scale.x=1 is modifying the Vector2 and would have no effect on the scale of the object. Meaning that you should do this:
skin.scale = Vector2(skin.scale.x + 1, skin.scale.y)
Or this:
var skin_scale = skin.scale
skin_scale.x += 1
skin.scale = skin_scale
Which I bet people using C# would find familiar.
But you don't need to do that in GDScript. Godot will call set_scale, which is what most people expect. It is a feature!
So, you set scale, and Godot will call set_scale:
void Node2D::set_scale(const Size2 &p_scale) {
if (_xform_dirty) {
((Node2D *)this)->_update_xform_values();
}
_scale = p_scale;
// Avoid having 0 scale values, can lead to errors in physics and rendering.
if (Math::is_zero_approx(_scale.x)) {
_scale.x = CMP_EPSILON;
}
if (Math::is_zero_approx(_scale.y)) {
_scale.y = CMP_EPSILON;
}
_update_transform();
_change_notify("scale");
}
The method _change_notify only does something in the editor. It is the Godot 3.x instrumentation for undo/redo et.al.
And set_scale will call _update_transform:
void Node2D::_update_transform() {
_mat.set_rotation_and_scale(angle, _scale);
_mat.elements[2] = pos;
VisualServer::get_singleton()->canvas_item_set_transform(get_canvas_item(), _mat);
if (!is_inside_tree()) {
return;
}
_notify_transform();
}
Which, as you can see, will update the Transform2D of the Node2D (_mat). Then it is off to the VisualServer.
And then to _notify_transform. Which is what propagates the change in the scene tree. It is also what calls notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED) if you have enabled it with set_notify_transform. It looks like this (this is from "canvas_item.h"):
_FORCE_INLINE_ void _notify_transform() {
if (!is_inside_tree()) {
return;
}
_notify_transform(this);
if (!block_transform_notify && notify_local_transform) {
notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED);
}
}
And you can see it delegates to another _notify_transform that looks like this (this is from "canvas_item.cpp"):
void CanvasItem::_notify_transform(CanvasItem *p_node) {
/* This check exists to avoid re-propagating the transform
* notification down the tree on dirty nodes. It provides
* optimization by avoiding redundancy (nodes are dirty, will get the
* notification anyway).
*/
if (/*p_node->xform_change.in_list() &&*/ p_node->global_invalid) {
return; //nothing to do
}
p_node->global_invalid = true;
if (p_node->notify_transform && !p_node->xform_change.in_list()) {
if (!p_node->block_transform_notify) {
if (p_node->is_inside_tree()) {
get_tree()->xform_change_list.add(&p_node->xform_change);
}
}
}
for (CanvasItem *ci : p_node->children_items) {
if (ci->top_level) {
continue;
}
_notify_transform(ci);
}
}
So, no. There is no check to ignore the change if the value is the same.
However, it is worth noting that Godot invalidates the global transform instead of computing it right away (global_invalid). This is does not make multiple updates to the transform in the same frame free, but it makes them cheaper than otherwise.
I also remind you that looking at the source code is no replacement for using a profiler.
Should you check? Perhaps… If there are many children that need to be updated the extra lines are likely cheap enough. If in doubt: measure with a profiler.

Kotlin Concurrency: Any standard function to run code in a Lock?

I've been searching for a function that takes an object of type Lock
and runs a block of code with that lock taking care of locking and also unlocking.
I'd implement it as follows:
fun <T : Lock> T.runLocked(block: () -> Unit) {
lock()
try {
block()
} finally {
unlock()
}
}
Used like this:
val l = ReentrantLock()
l.runLocked {
println(l.isLocked)
}
println(l.isLocked)
//true
//false
Anything available like this? I could only find the synchronized function which cannot be used like this.
You are looking for withLock, which has the exact implementation you've written yourself, except it has a generic parameter for the result of the block instead of the receiver type.
You can find other concurrency related methods of the standard library here, in the kotlin.concurrent package.

File or module level 'feature' possible?

Some optimizations/algorithms make code considerably less readable, so it's useful to keep the ability to disable the complex-and-unwieldily functionality within a file/module so any errors introduced when modifying this code can be quickly tested against the simple code.
Currently using const USE_SOME_FEATURE: bool = true; seems a reasonable way, but makes the code read a little strangely, since USE_SOME_FEATURE is being used like an ifdef in C.
For instance, clippy wants you to write:
if foo {
{ ..other code.. }
} else {
// final case
if USE_SOME_FEATURE {
{ ..fancy_code.. }
} else {
{ ..simple_code.. }
}
}
As:
if foo {
{ ..other code.. }
} else if USE_SOME_FEATURE {
// final case
{ ..fancy_code.. }
} else {
// final case
{ ..simple_code.. }
}
Which IMHO hurts readability, and can be ignored - but is caused by using a boolean where a feature might make more sense.
Is there a way to expose a feature within a file without having it listed in the crate?(since this is only for internal debugging and testing changes to code).
You can use a build script to create new cfg conditions. Use println!("cargo:rustc-cfg=whatever") in the build script, and then you can use #[cfg(whatever)] on your functions and statements.

In java, return value within synchronized block seems like bad style. Does it really matter?

I have a Collections.synchronizedList of WeakReference, _components;
I wrote something like the following, expecting the complier to complain:
public boolean addComponent2(Component e) {
synchronized (_components) {
return _components.add(new WeakReference<Component>(e));
}
}
But the compiler is perfectly satisfied. Note that List.add() returns TRUE. So ok, any exit from a synchronized block releases the lock, but doesn't this LOOK strange? It's kind of like a "hole" in the block, similar to using return in a loop.
Would you be happy maintaining code like this?
It's absolutely fine - as is returning from a loop, or from a try block which has an appropriate finally block. You just need to be aware of the semantics, at which point it makes perfect sense.
It's certainly simpler code than introducing a local variable for the sake of it:
// Ick - method body is now more complicated, with no benefit
public boolean addComponent2(Component e) {
boolean ret;
synchronized (_components) {
ret = _components.add(new WeakReference<Component>(e));
}
return ret;
}
There is nothing wrong with returning inside a synchronized block. The lock will be released correctly.

Best pattern for simulating "continue" in Groovy closure

It seems that Groovy does not support break and continue from within a closure. What is the best way to simulate this?
revs.eachLine { line ->
if (line ==~ /-{28}/) {
// continue to next line...
}
}
You can only support continue cleanly, not break. Especially with stuff like eachLine and each. The inability to support break has to do with how those methods are evaluated, there is no consideration taken for not finishing the loop that can be communicated to the method. Here's how to support continue --
Best approach (assuming you don't need the resulting value).
revs.eachLine { line ->
if (line ==~ /-{28}/) {
return // returns from the closure
}
}
If your sample really is that simple, this is good for readability.
revs.eachLine { line ->
if (!(line ==~ /-{28}/)) {
// do what you would normally do
}
}
another option, simulates what a continue would normally do at a bytecode level.
revs.eachLine { line ->
while (true) {
if (line ==~ /-{28}/) {
break
}
// rest of normal code
break
}
}
One possible way to support break is via exceptions:
try {
revs.eachLine { line ->
if (line ==~ /-{28}/) {
throw new Exception("Break")
}
}
} catch (Exception e) { } // just drop the exception
You may want to use a custom exception type to avoid masking other real exceptions, especially if you have other processing going on in that class that could throw real exceptions, like NumberFormatExceptions or IOExceptions.
Closures cannot break or continue because they are not loop/iteration constructs. Instead they are tools used to process/interpret/handle iterative logic. You can ignore given iterations by simply returning from the closure without processing as in:
revs.eachLine { line ->
if (line ==~ /-{28}/) {
return
}
}
Break support does not happen at the closure level but instead is implied by the semantics of the method call accepted the closure. In short that means instead of calling "each" on something like a collection which is intended to process the entire collection you should call find which will process until a certain condition is met. Most (all?) times you feel the need to break from a closure what you really want to do is find a specific condition during your iteration which makes the find method match not only your logical needs but also your intention. Sadly some of the API lack support for a find method... File for example. It's possible that all the time spent arguing wether the language should include break/continue could have been well spent adding the find method to these neglected areas. Something like firstDirMatching(Closure c) or findLineMatching(Closure c) would go a long way and answer 99+% of the "why can't I break from...?" questions that pop up in the mailing lists. That said, it is trivial to add these methods yourself via MetaClass or Categories.
class FileSupport {
public static String findLineMatching(File f, Closure c) {
f.withInputStream {
def r = new BufferedReader(new InputStreamReader(it))
for(def l = r.readLine(); null!=l; l = r.readLine())
if(c.call(l)) return l
return null
}
}
}
using(FileSupport) { new File("/home/me/some.txt").findLineMatching { line ==~ /-{28}/ }
Other hacks involving exceptions and other magic may work but introduce extra overhead in some situations and convolute the readability in others. The true answer is to look at your code and ask if you are truly iterating or searching instead.
If you pre-create a static Exception object in Java and then throw the (static) exception from inside a closure, the run-time cost is minimal. The real cost is incurred in creating the exception, not in throwing it. According to Martin Odersky (inventor of Scala), many JVMs can actually optimize throw instructions to single jumps.
This can be used to simulate a break:
final static BREAK = new Exception();
//...
try {
... { throw BREAK; }
} catch (Exception ex) { /* ignored */ }
Use return to continue and any closure to break.
Example
File content:
1
2
----------------------------
3
4
5
Groovy code:
new FileReader('myfile.txt').any { line ->
if (line =~ /-+/)
return // continue
println line
if (line == "3")
true // break
}
Output:
1
2
3
In this case, you should probably think of the find() method. It stops after the first time the closure passed to it return true.
With rx-java you can transform an iterable in to an observable.
Then you can replace continue with a filter and break with takeWhile
Here is an example:
import rx.Observable
Observable.from(1..100000000000000000)
.filter { it % 2 != 1}
.takeWhile { it<10 }
.forEach {println it}

Resources