The gap of several cycles in Ceylon

Say I have several nested loops forin Ceylon. How to break out of all cycles:

variable Integer? something = null;
for (i in 0:3) {
  for (j in 0:3) {
    for (k in 0:3) {
      something = someFunction(i,j,k);
      if (something exists) {
        // break out of everything, we found it
      }
    }
  }
}
+4
source share
3 answers

One way to do this is to wrap it all in a closure, and then call it using return when you want to break out of everything:

Integer? doLoops() {
  for (i in 0:3) {
    for (j in 0:3) {
      for (k in 0:3) {
        Integer? something = someFunction(i,j,k);
        if (something exists) {
          return something;
        }
      }
    }
  }
  return null;
}
Integer? something = doLoops();

Since Ceylon supports locking, you can also read and write other values ​​outside the function in the area where it is doLoopsdefined.

+6
source

Instead, you can use the syntax for understanding and processing the stream:

Iterable<Integer?> stream = {
    for (i in 0:3) for (j in 0:3) for (k in 0:3) someFunction(i,j,k)
};

Integer? = stream.coalesced.first;

This will work as expected because { for ... }comprehension creates Iterableone that is lazily evaluated.

coalesced , null .

.

+5

- else for:

shared void run() {
    variable Integer? x = null;
    for (i in 0:3) {
        for (j in 0:3) {
            for (k in 0:3) {
                value n = i*j*k;
                if (n > 18) {
                    x = n;
                    break;
                } else {
                    continue;
                }
            } else {
                continue;
            }
            break;
        } else {
            continue;
        }
        break;
    } else {
        x = null;
    }
    print(x);
}

,

else {
    continue;
}
break;

for s.

(: , , - x , something - variable, . typechecker , .)

? else for , - break. , continue ; - , - break .

, ceylon/ceylon # 3223:

for (a in b) {
    for (x in y) {
        if (something) {
            break;
        }
    } then { // opposite of else: runs iff there was a break in the inner loop
        break;
    }
}

:

  • , . for {} else {} , , , .
  • ( ), .
  • , : else , .
+3

Source: https://habr.com/ru/post/1625661/


All Articles