number ranges
Salih Dincer
salihdb at hotmail.com
Wed Jan 19 12:51:08 UTC 2022
On Tuesday, 18 January 2022 at 23:13:14 UTC, Ali Çehreli wrote:
>
> But I like the following one better because
> it is fast and I think it works correctly.
Is it okay to swap places instead of throwing an error? Let's
also implement BidirectionalRange, if okay. This great struct
will now run 4x4 like a Jeep. 😀
Moreover, the iota doesn't even care if define char type. And no
throwing an error.
The real question to ask is:
"Does it reverse the result
in case ```a > b``` like we
did with foreach_reverse()"
Salih
```d
import std;
struct InclusiveRange(T) {
T front, last;
this(U)(in U front, in U last) {
this.front = front;
this.last = last;
if(empty) toogleFrontLast();
}
bool empty() {
return front > last;
}
void popFront() {
if(!empty) ++front;
}
T back() {
return last;
}
void popBack() {
if(!empty) --last;
}
void toogleFrontLast() {
auto temp = this.last;
this.last = this.front;
this.front = temp;
}
}
auto inclusiveRange(T)(T first, T last) {
return InclusiveRange!T(first, last);
}
enum a = 8; // ASCII 80: P
enum b = 7; // ASCII 70: F
alias type = char;
alias test = inclusiveRange;
void main() {
string str; // for tests...
auto io = iota!type(a * 10, b * 10);
io.writeln("\n", typeof(io).stringof, "\n");
str = to!string(io);
assert(str == "[]"); // OMG, why?
auto ir = test!type(a * 10, b * 10);
ir.writeln("\n", typeof(ir).stringof, "\n");
str = to!string(ir);
assert(str == "FGHIJKLMNOP"); // Ok
foreach_reverse(c; ir) str ~= c;
assert(str == "FGHIJKLMNOPPONMLKJIHGF"); // Ok
}
```
More information about the Digitalmars-d-learn
mailing list