3 ms·
Yup, strongly agree that having a single iterate-over-collection construct and a nice notation for ranges has big advantages. (I did say that before, but I gues
by gjm11 12y ago
Yup, strongly agree that having a single iterate-over-collection construct and a nice notation for ranges has big advantages. (I did say that before, but I guess it was buried in among a lot of other stuff.)
The drawback is that the nice terse range notation leaves it unclear whether your ranges are inclusive or exclusive (and I conjecture that if you asked 100 experienced software people to guess which of 1..8 and 1...8 is which, you'd get something close to 50% jumping each way).
What I'd really like is a syntax for ranges that has clarity comparable to "for (0 <= i < n)" but terseness comparable to "0...n", without being too much a special case. Unsurprisingly, I've never yet seen one.
Here's a less-than-half-baked proposal, though. Probably too quirky for Wren.
1. Some syntax like [1 <= i < n] -- inequality operators, delimited in an appropriate way -- indicates a range object and, at least at parse time, carries around an indication of the name of the index variable. (Index variables if we allow fancy stuff like [1 <= i < j < n].)
2. "for <literal-range>" is syntactic sugar for "for (i in <literal-range>)" where i is the name of the variable. (If we allow fancy multi-variable ranges, this only works if your for-loop is able to bind multiple variables as with "for (i,j) in [(1,2),(3,4)]" in Python.)
3. Perhaps "for <literal-range> where <condition>" is likewise syntactic sugar for "for (i in <literal-range>.where(<condition>))" or something.
4. So far, this is less general than your .. and ... operators because it's all special-cased for integers. Except there's no reason why it needs to be. Perhaps, e.g., [a < i < b] invokes a magical method on a, which gets passed the upper bound b and an indication of direction and inclusivity at each end. My fancy multi-variable forms can be implemented in terms of this without any further magic, though not maximally efficiently.
[EDITED to add: It happens that I quite often have use for numeric iteration, and even for the fancy multi-variable forms I've described here. But I'm probably atypical.]