Articles

Affichage des articles du avril, 2019

Inclusive looping in D

D lets us write for loops in the following form : foreach(i; 0 .. 5) { //do something with i } While convenient, I sometimes find myself needing to iterate over a range inclusively, which means that I want the upper bound to be included in the loop. Kotlin supports both inclusive and exclusive looping with the .. and until operators. Nim's .. and .. Naive solution The following hack makes use of UFCS to provide a readable solution to the problem outlined above : T inc(T)(T input) { return cast(T)(input + 1); } void main() { foreach(i; 0 .. 5.inc) { writeln(i); } } inc stands for inc lusive, but it can also be thought of as inc rement since that's what really happens here. UFCS lets us write 5.inc instead of the more verbose inc(5) alternative. The code seems to behave well, but upon closer inspection, you'll notice that it will cause a premature loop exit on overflows. The following code won't print anything because size.inc ov...