Re: 2.6 feature request: foreach
- Posted by Robert Craig <rds at RapidEuphoria.com> Jul 14, 2005
- 472 views
D. Newhall wrote: > I think that the next release should have something new and useful to the > language. > Sure, you could do "continue" or "next" or something but will everyone use > them? When > I was looking at all the code I've written I realized that maybe around half > of all > my "for" loops were being used to reference each element in a sequence one > after another. > Due to this I think that a "foreach" statement would be a VERY useful addition > to the > language that I'm sure everyone would use. > > It's syntax could go like so: > > Instead of > > sequence line > line = gets(0) > for i=1 to length(line) > if line[i] = -- something > -- code goes here > end if > end for > > One would type > > sequence line > line = gets(0) > foreach element in line do > if element = -- something > -- code goes here > end if > end foreach > > Here "element" would implicitly be declared as an object and act just like the > current > loop variable in "for". However, after every iteration of the loop "element" > will be > set to the next next element in "line". A consideration would be to optimize > expressions > of the type "foreach obj in reverse(seq)do" Thanks for the suggestion. I thought about something like this about 10 years ago. At first it looked like a good idea, but after trying various examples and thinking it through, I felt it might cause confusion. Short simple examples like the one above are ok, but what if you have a loop with 100 statements in it? The aliasing of one name for another might be hard to remember. In the middle of a long section of code you could easily forget that element = 99 really means (something like) line[i] = 99 (I assume you could read or write these loop variables). Or element[5] += 1, really means (more or less) line[i][5] += 1 And could you change line in the middle of the loop? Would the value of line be locked in. What if you saw: line[j] = element Would you instantly understand what it meant? These issues made me think the feature was not such a good thing to add to a language that is supposed to be simple. Thanks, Rob Craig Rapid Deployment Software http://www.RapidEuphoria.com