Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break out of multiple for loops in Ceylon

Tags:

ceylon

Let's say I have I several nested for loops in Ceylon. How do I break out of all the loops:

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
      }
    }
  }
}
like image 527
drhagen Avatar asked Dec 09 '22 00:12

drhagen


1 Answers

One way to do it is to wrap the whole thing 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();

Because Ceylon supports closures, you can also read and write other values outside the function in the scope where doLoops is defined.

like image 144
drhagen Avatar answered Mar 20 '23 05:03

drhagen