Maybe we don't need foreach ;-)
Bill Baxter
dnewsgroup at billbaxter.com
Mon Oct 30 19:38:35 PST 2006
Walter Bright wrote:
> Bill Baxter wrote:
>> Just like some people have said, you can do everything with 'for'.
>> Well, actually maybe you can. It occurred to me that foreach and for
>> really don't clash. One requires two semicolons, the other only one.
>> So instead of a foreach we could have had
>>
>> for(a; aggregate)
>> {
>>
>> }
>
> That looks like a syntax error for one used to for loops.
For one used to C for loops, yes. But Python for loops look like
for a in aggregate: ...
Bash for loops look like
for f in list; do ... done
There is certainly precedent for using 'for' synonymously with 'for each'.
>> or if the keyword 'in' had been used for the new construct instead of
>> borrowing from c's ; syntax it would be:
>>
>> for(a in aggregate)
>> {
>> ...
>> }
>
> 'in' is already an operator, so that wouldn't work.
It already has multiple duties as a storage type, so that alone
shouldn't be an issue.
But I suppose you're right that it won't work here since a standard for
loop can start with an Expression, which can contain an 'in'. So this
would require arbitrary lookahead to see if there are any ';''s coming
or not.
Anyway, it wouldn't be a problem in a foreach :-). foreach can only
start with ForeachTypeList so there would be no problems with:
foreach(a in aggregate) { }
as far as I can tell.
>> which could quite peacefully coexist with good-ole
>>
>> for (int i=0; i<10; i++)
>> {
>> }
>>
>> Oh well. Too much momentum behind foreach and foreach_reverse now, I
>> suppose, to make such a simplification.
>
> foreach is a fairly well understood term, I think it needs less
> explanation than a variant on for.
Perhaps. But we're talking about epsilon vs 2*epsilon in terms of the
amount of explanation required.
One thing foreach has going for it is that it makes it feasible to
replace the ';' with the 'in' keyword. :-)
--bb
More information about the Digitalmars-d
mailing list