I'm converting Advent of Code solutions from VBA (twinBasic) to Nim
I have a bit of a headscratcher when it comes to implementing the Step functionality in 'for x to y step z' because in VBA step can be a positive or a negative value wheres nim uses countup or countdown iterators with the step value always being a positive number
Dim myXStep As Long = If(s.X1 <= s.X2, 1, -1)
For myXCoord = s.X1 To s.X2 Step myXStep
I tried being clever with this code in nim
var myXStep:iterator [T](a, b:T): T = if s.X1 <= s.X2: [T]countup(a,b:T) else: [T]countdown(a,b:T)
so that I could then write
for myX in myXstep(s.X1,s.X2)
but it doesn't work, even when I convert the 1 line version to a multiline version
I have elsewhere successfully used something similar to the above to provide procs as a parameter but I'm obviously not quite there yet with the above attempts.
Advice would be welcome.
That's a neat solution but isn't appropriate in this case. The iteration has to be X1 to X2 because the x values are tied to Yvalues and your suggestion would change the x,y pairs.
In the meantime I've come up with the ghastly apparition of
iterator myStep( a,b: int):int=
var a1 = a
var b1 = b
if a<=b:
while a1<=b1:
yield a1
inc a1
else:
while a1>b1:
yield a1
dec a1
but won't be able to test it until monday <sigh>Equivalent to your solution, but more concise:
iterator mystep(a, b: int): int =
for i in countup(a, b):
yield i
for i in countdown(a, b + 1):
yield i
Version with only one yield
iterator myStep(a, b:int):int =
let step = if a < b: 1 else: -1
var i = a
while (if 1 == step: i <= b else: i >= b):
yield i
i += step
That worked fine. I also used a version of it in C# to resolve a similar nastinees.
Cheers.