Mailing List Archive: 49091 messages
  • Home
  • Script library
  • AltME Archive
  • Mailing list
  • Articles Index
  • Site search
 

[REBOL] Re: Breaking out of loops

From: joel:neely:fedex at: 28-Nov-2002 9:19

Hi, Ted, Well, it depends... ;-) Ted Landis wrote:
> Greetings again, > > When breaking out of a loop what is the best way to indicate this? > for example: > > loop 100 [ > ... > if a = b [break] > ... > ] > > How do I tell if the loop was completed (all 100 iterations) or was > terminated prematurely? >
One possibility is based on the fact that the value yielded by an evaluation of LOOP _n_ _block_ is the last expression evaluated in the block. print join either loop 100 [ ... if ... [break/return true] ... false ] ["Premature"]["Normal"] " termination!" so that the value of the entire loop evaluation is TRUE/FALSE based on whether the block did/didn't bail out. Another possibility is loopcount: 0 repeat i 100 [ ... if ... [break] ... loopcount = i ] at which point LOOPCOUNT contains the number of complete passes thru the loop that were completed. I realize some folks might argue No fair! You replaced LOOP with REPEAT to get that result! to which I would reply The whole point of LOOP is that it lets you evaluate a block some specified number of times *without*caring* about the value of a "counter" variable. If we *do* care about that, then we should use a form that was designed with the concept of the counter in mind. I would back up and ask myself "Why do I care?" and then do something appropriate for that goal. For example, if I'm searching a block of numbers for a negative value, I can stop searching when one is found. Falling through the entire loop means that no such value occurred. This could be handled by wrapping the looping expression in a function that returns either an appropriate value for "success" or a "bottom" value for "failure", as in first-negative: func [b [block!]] [ foreach item b [if negative? item [return item]] none ] either found? negval: first-negative [6 2 7 4 3 -2 2 5] [ print ["The negative value" negval "was found"] ][ print "No negative values in block!" ] Try thinking more of strategy and less of tactics, and problems such as this tend to melt away... HTH! -jn- -- ; Joel Neely joeldotneelyatfedexdotcom REBOL [] do [ do func [s] [ foreach [a b] s [prin b] ] sort/skip do function [s] [t] [ t: "" foreach [a b] s [repend t [b a]] t ] { | e s m!zauafBpcvekexEohthjJakwLrngohOqrlryRnsctdtiub} 2 ]