var
found = false
rng: SomeRange
for sr in SomeRange:
if <some_condition>:
found = true
rng = sr
break
if found:
# Use rng
In C I'd write this like so:
int rng = LOW;
while (rng < HIGH)
{
if (<some_condition>) break;
rng++;
}
if (rng < HIGH)
// Use rng
I can't use this construct:
var rng = SomeRange.low
while rng < SomeRange.high:
if <some_condition>: break
inc rng
if (rng < SomeRange.high)
# Use rng
As calling inc() on rng.high throws an error (this changed only recently).
const somecondition = true
type MyRange = range[0..2]
var x: MyRange
while x < MyRange.high:
if somecondition: break
inc x
if x == MyRange.high:
discard
echo x
const somecondition = true
type MyRange = range[0..2]
var
it: MyRange
found:bool
for itm in MyRange.low .. MyRange.high:
if somecondition:
found = true
it = itm
break
if found:
discard
echo it
type SomeRange = [0..1]
var rng = SomeRange.high
inc rng
Also, my third sample should read like so (too C-centric some times...):
type SomeRange = range[0..1]
var rng = SomeRange.low
while rng <= SomeRange.high:
if false: break
inc rng
if (rng <= SomeRange.high):
# Use rng
Sorry for that. I hope you get the idea NOW.
import typetraits
type SomeRange = range[0..1]
var
rng = SomeRange.high.int # Now an int!
ary: array[SomeRange, int]
echo rng.type.name
echo ary[rng + 1] # Crashes on run!
echo ary[2] # Error on compile!
What about something like this:
var
rng = SomeRange.oob # Typesafe initializer to an "Out-of-bounds" value
var x = low(T)
while x <= high(T):
echo x
inc x
Needs to be replaced by something like this:
var x = low(T).int
while x <= high(T).int:
echo x.T
inc x
This is most often wrapped up in an iterator so it's not too bad IMHO. Note that r <= high(r) and r >= low(r) always holds and so the compiler is free to optimize it away!
type SomeRange = range['a'..'b']
var
rng = SomeRange.high.char
ary: array[SomeRange, int]
inc rng
echo ary[rng] # No longer crashes on run...
Well you keep changing the topic! Now it's release vs debug mode. It's well known that -d:release trades correctness for speed. You test in debug mode and then turn on release for speed. If you need the speed.
how would I handle this w/o loosing type-safety?
type
ArrayRange = 0..10
IndexRange = -1..10
Arr = array[ArrayRange, int]
let i = IndexRange.low