Breaking out of a map or other iteration

Right – my point is mainly that you’re wasting cycles, which I believe is avoided by mixing in NoStackTrace. (Which I believe is a marker trait that tells the system not to bother building a stack trace, since it isn’t going to be used.)

Sounds like a good idea, but I don’t completely understand the intended syntax. Do you mean I should use the following?

  def block[A](body:(A=>Nothing)=>A):A = {
    import scala.util.control.NoStackTrace

    class NonLocalExit(val data:A) extends Exception with NoStackTrace {}
    def ret(data:A):Nothing = {
      throw new NonLocalExit(data)
    }
    try{
      body(ret)
    }
    catch{
      case nonLocalExit: NonLocalExit => nonLocalExit.data
    }
  }

Right – basically, NoStackTrace overrides the expensive fillInStackTrace() function with a no-op, so constructing the Exception becomes much cheaper. Source code

It’s a really good enhancement to my code. I’m happy to have it. thanks.

What about a tactic like this (which was hinted at earlier in this thread)

val someExistingSequence = Seq( ... )

      Range.inclusive( low, high )
        .view
        .map( p =>
          {
            someNetworkFetchReturningASequence( ...p, pageLimit... )
          }
        )
        .takeWhile( _.nonEmpty )
        .fold( someExistingSequence ) ( ( x,y ) => x ++ y )

Here, I want to map the range of pages to be requested to actual expensive requests made until a request in the sequence returns an empty Sequence which indicates that all the subsequent requests will also be pointless (assuming we can predict the behavior of the server).

If you need to pass through the functional pipeline separate values for the values to be reduced and values to be checked in the takeWhile filter, then either return a proper compound type from the expensive operation or return a Tuple with as many slots as needed to pass results and conditions.

I come from guava and Java streams where these stream concepts are implicitly lazy. So I added “.view” here on the Range to ask it to be lazy.

Yes, I see that this is just @MarkCLewis’ suggestion expanded out.