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 ..< operators behave respectively like Kotlin's .. and until. Swift supports a similar construct as well. D doesn't support one natively, but it shouldn't be too difficult for us to come up with something. 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 verb