number ranges
Ali Çehreli
acehreli at yahoo.com
Fri Jan 21 17:25:20 UTC 2022
On 1/21/22 08:58, Salih Dincer wrote:
> ```d
> auto inclusiveRange(T)(T f, T l, T s = cast(T)0)
> in(!isBoolean!T) {
'in' contracts are checked at runtime. The one above does not make sense
because you already disallow compilation for 'bool' below.
You could add a template constraint there:
auto inclusiveRange(T)(T f, T l, T s = cast(T)0)
if(!isBoolean!T) {
(Note 'if' vs. 'in'.)
However, people who instantiate the struct template directly would
bypass that check anyway.
> static assert(!isBoolean!T, "\n
> Cannot be used with bool type\n");
> if(!s) s++;
> return InclusiveRange!T(f, l, s);
> }
> bool opBinaryRight(string op:"in")(T rhs) {
> foreach(r; this) {
> if(r == rhs) return true;
> }
> return false;
> }
Ouch! I tried the following code, my laptop got very hot, it's been
centuries, and it's still running! :p
auto looong = inclusiveRange(ulong.min, ulong.max);
foreach (l; looong) {
assert(l in looong);
}
> size_t length() inout {
> auto len = 1 + (last - first) / step;
> return cast(size_t)len;
> }
Does that not return 1 for an empty range?
Additionally, just because we *provide* a step, now we *require*
division from all types (making it very cumbersome for user-defined types).
> // Pi Number Test
> auto GregorySeries = inclusiveRange!double(1, 0x1.0p+27, 2);
Very smart! ;) So, this type can support floating point values if we use
that syntax.
Ali
More information about the Digitalmars-d-learn
mailing list