ForExpr
From Erights
(Redirected from For loop)
ForExpr is a nonkernel node which executes code for each element in a collection or other object implementing iterate/1.
"for" (optKeyPattern "=>")? valuePattern "in" collection "{" body "}" ({optBreakCatch an EMatcher}: "catch" pattern "{" expr "}")?
XXX We need to formalize the grammar definitions used in our spec
Contents |
Fields
- optKeyPattern :nullOk[Pattern]
- valuePattern :Pattern
- collection :nullOk[EExpr]
- body :EExpr
- optBreakCatch :nullOk[EMatcher]
Expansion
XXX Define the expansion of ForExpr
Static constraints
- collection may not use nouns bound by optKeyPattern or valuePattern, or vice versa.
Tests
The function provided to (the value of collection)'s iterate/1 method throws if called after iterate/1 has returned.
? var captured := null
? def capturer {
> to iterate(f) :void {
> captured := f
> f("a", "b")
> }
> }
# value: <capturer>
? for x => y in capturer { println(x, " -> ", y) }
# stdout: a -> b
#
? captured("c", "d")
# problem: For-loop body isn't valid after for-loop exits.
The return value of iterate/1 is not the return value of the for loop; the loop returns null unless a return value is given by __break.
? def confuser extends [1,2,3] {
> to iterate(f) {
> super.iterate(f)
> return __Portrayal
> }
> }
# value: <confuser>
? def optKeyOf(collection, toFind) {
> return for key => val in collection {
> if (val == toFind) {
> break key
> }
> }
> }
? optKeyOf(confuser, 1)
# value: 0
? [optKeyOf(confuser, 43)]
# value: [null]

