Re: foreach
- Posted by CChris Jul 24, 2008
- 1021 views
While we are talking about foreach, maybe we should just hash it out? I am not sure of syntax issues, the foreach given by ryan is pretty standard?
A development forum would nice at this point
I wouldn't call most of the below "issues", but obviously expected stuff. This is why I was confused by the mention of syntax issues.
[/quote]
One issue is whether the loop variable can be assigned to. In the current for loop, one cannot assign to the loop variable, but that restriction might not be appropriate in a foreach.
foreach x in s do if x > n then x /= 2 end if end for
ought to be equivalent to
for x = 1 to length(s) do if s[x] > n then s[x] /= 2 end if end for
Since x is not an index variable, it doesn't need to be read only. Why mixing things up?
Another issue is whether we can also get the current index value inside the loop.
foreach x[i] in s do if i > 1 then if x > s[i-1] then x /= 2 end if end if end for
I think I'd find
foreach x in s index i do
clearer, but wouldn't mind. The index clause woould be optional, and the foreach loop index would be read only.
Yet another issue is whether we can do parallel processing on a set of sequences.
foreach x in s, y in t do if x > y then x = y end if end for
I would say yes, but what happens when s and t have different lengths? I would quit whenever any parallelly processed sequence is exhausted. Also, the extra comma is not usual in Eu, can be removed.
Yet another issue is whether we can process the sequence in reverse order.
foreach x in reversed s do if find(x, " \t\r\n") = 0 then exit end if x = ' ' end for
Why not?
Yet another issue is what happens when the length of the sequence changes within the loop?
foreach x in s do if x > 1 then s = func(s) end if end for
This is the only item I'd consider an issue.
My understanding would be this: foreach dumbly traverses the sequence, one element after the previous/next, and quits when no more is found. This behaviour is, I think, the only one we can implement efficiently, and it may be the desired thing in some cases. It won't be always so, but then why not use a while loop? I assume these will be uncommon enough cases.
Dynamic s-es will be handled much more efficiently than having to test always for valid indexes - the interpreter does it anyway, so that's duplicated code.
And I'm sure there are still a few other corner cases worthy of consideration.
Even though I'd definitel use foreach it it was there, it can wait past 4.0 alpha, as it does not modify current code. Except for variables/routines currently named "foreach", of course.
Actually, there is another issue which could be raised, and which is common to for loops: should the scope for the index variable be extended? And should the object variable in the foreach construct be scoped inside the foreach loop proper? But this is a connected issue for another thread.
CChris