for/break

Mark S. Miller markm@erights.org
Wed, 02 Dec 1998 10:44:32 -0800


At 01:35 AM 12/2/98 , Ka-Ping Yee wrote:
>
>[] How do you break out of a "for" loop?
>
>If "while" comes with a "break", shouldn't "for" come with a
>"break" too?  I noticed in editing these pages of documentation
>that there was no mention of that.
>
>Being able to return a value from the inside of a "for" loop
>is an important ability that will stop people from complaining
>that their key-pattern and value-pattern are locked in the
>inner scope...

[+] It does what you want & expect.
"break" and "continue" in a "for" loop act just as they do in a while loop.

	? define firstEven(list) {
	>     for i in list {
	>         if (i %% 2 == 0) {
	>             break(i)
	>         }
	>     }
	> }
	# value: <firstEven>

	? firstEven([1, 3, 5, 6, 9])
	# value: 6

	? firstEven([1, 3, 5, 7, 9]) == null
	# value: true

This is implied by the for-loop expansion, which looks fine in the pdf, but 
was totally garbled in translation to html.  It is:

escape break {
    collection-expression iterate(define _(k,v) {
        if (k =~ key-patt && v =~ value-patt) {
            escape continue {
                body-expression
            }
        }
    })
}

Where "k" and "v" are temporary variable names guaranteed not to conflict 
with any written by the user.

In any case, It'd be great for you to add explanations of "break" and 
"continue" to your for loop sections.  Thanks.