Why foreach(c; someString) must yield dchar

dsimcha dsimcha at yahoo.com
Thu Aug 19 07:15:30 PDT 2010


== Quote from dsimcha (dsimcha at yahoo.com)'s article
> I've been hacking in Phobos and parallelfuture and I've come to the conclusion
> that having typeof(c) in the expression foreach(c; string.init) not be a dchar
> is simply ridiculous.  I don't care how much existing code gets broken, this
> needs to be fixed.

Here's another good one.  This one uses Lockstep, which is in the SVN version of
std.range and is designed to provide syntactic sugar for iterating over multiple
ranges in lockstep via foreach.

string str1, str2;
foreach(c1, c2; lockstep(str1, str2)) {}

// c1, c2 are dchars since Lockstep relies on range primitives.

foreach(c; str1) {}
// c is a char since the regular foreach loop doesn't use range
// primitives.

I'm starting to think the inconsistency between ranges and foreach is really the
worst part.  When viewed in isolation, Andrei's changes to std.range to make
ElementType!string == dchar, etc. were definitely the right thing to do.  However,
if we can't fix foreach, it might be a good idea to undo them because in this case
I think such a ridiculous, bug producing inconsistency is worse than doing The
Wrong Thing consistently.



More information about the Digitalmars-d mailing list