#2294 List.each breakout

shakeshuck Wed 4 Jun 2014

Is there a way to break from processing a list via .each? Using a return from the closure (obviously) moves on to the next item.

I could do a for loop instead but that's not as tidy and leaves me open to index errors.

Am I missing an elegant alternative (like Java's "for (a: b)") that you can break from?

tomcl Wed 4 Jun 2014

sys::List.eachWhile method does what you want, and does the right thing so it can be nested!

SlimerDude Wed 4 Jun 2014

Or you could use List.find() also. They're both pretty simliar if you're not going to use the return value.

[1, 2, 3].find |Int int -> Bool| {
  ...
  if (int == 2)
    return true
  ...
  return false
}

[1, 2, 3].eachWhile |Int int -> Bool?| {
  ...
  if (int == 2)
    return true // return anything that's not null
  ...
  return null
}

shakeshuck Wed 4 Jun 2014

Thanks, guys.

I couldn't get it working exactly as per your examples - the compiler was complaining about returns in it-blocks - (I must still be missing some language fundamentals at the moment, but of course I'd rather try to get things working rather than read the manual!). I have managed to do it using eachWhile, but it was a little messier than your code:

rows.eachWhile |Row row -> Bool?| {

so that it would accept null/non-null returns and not complain about the it-block.

SlimerDude Wed 4 Jun 2014

Yep, that's right. I missed that bit off - oops!

brian Wed 4 Jun 2014

By convention, we'd typically write something like this:

rows.eachWhile |row|
{
  if (my row) return non-null result
  return null
}

shakeshuck Thu 5 Jun 2014

Brian,

That was part of my problem. It is of course possible (likely!) that I've structured my code badly, but removing the return Type i.e. making

|Row row -> Bool?|

into

|Row row|

gives me a compiler error:

Cannot return a value from Void method

Login or Signup to reply.