digitalmars.D - Re: Range Type
- bobcat <a b.com> Mar 24 2008
Nice! I was also wishing for ranges in D, but didn't know how it would behave with the rest of the languages. Doing foreach(i, 1..20) would also be a natural fit for this, where foreach also accepts a slice :). ( I know there is already something similar in D 2.0. ) Janice Caron Wrote:I know this has cropped up before (in discussions about multiple dimension arrays), but adding a range type would also really help with the whole business of returning slices. (See the many other threads currently buzzing with this topic). A range is nothing more than a two-element struct struct Range(T,U=T) { T begin; U end; } However, if you throw in some extra language support, it gets really, really useful. Basically, you want the ".." infix operator always to create a range. Thus auto x = 3 .. 4; creates a Range!(int) with values { 3, 4 }. In general (a .. b) should evaluate to a Range!(typeof(a),typeof(b)) with values { a, b }. Finally, you also want [] and opSlice() to accept Range! parameters, so that s = s[a..b]; can always be rewritten as auto t = a..b; s = s[t]; In general, opSlice(Range r) should be eqivalent to opSlice(r.begin, r.end). In my opinion language support for ranges (allowing .. to return a range, and allowing [] to accept a range) has advantages above and beyond those already discussed, and may also allow many other exciting possibilites we haven't even thought of yet.
Mar 24 2008