Hi there. I'm doing some experiments with Nim. Can anyone explain how this code:
for x, y in [0..10, 0..10]:
echo(x)
echo(y)
gives this output:
0 (a: 0, b: 10) 1 (a: 0, b: 10)
and is there a way to work this 2 or more items in a for loop? Thx
This will help you understand that code better:
import strformat, typetraits
let r = [0 .. 3, 0 .. 3]
echo fmt"r = {r}, of type `{$r.type}'"
for x, y in r:
echo fmt"x = {x}, of type `{$x.type}'"
echo fmt"y = {y}, of type `{$y.type}'"
Output:
r = [(a: 0, b: 3), (a: 0, b: 3)], of type `array[0..1, HSlice[system.int, system.int]]'
x = 0, of type `range 0..1(int)'
y = (a: 0, b: 3), of type `HSlice[system.int, system.int]'
x = 1, of type `range 0..1(int)'
y = (a: 0, b: 3), of type `HSlice[system.int, system.int]'
This is probably what you wanted:
import strformat, typetraits
for x in 0 .. 3:
for y in 0 .. 3:
echo fmt"x = {x}, of type `{$x.type}', y = {y}, of type `{$y.type}'"
Outputs:
x = 0, of type `int', y = 0, of type `int'
x = 0, of type `int', y = 1, of type `int'
x = 0, of type `int', y = 2, of type `int'
x = 0, of type `int', y = 3, of type `int'
x = 1, of type `int', y = 0, of type `int'
x = 1, of type `int', y = 1, of type `int'
x = 1, of type `int', y = 2, of type `int'
x = 1, of type `int', y = 3, of type `int'
x = 2, of type `int', y = 0, of type `int'
x = 2, of type `int', y = 1, of type `int'
x = 2, of type `int', y = 2, of type `int'
x = 2, of type `int', y = 3, of type `int'
x = 3, of type `int', y = 0, of type `int'
x = 3, of type `int', y = 1, of type `int'
x = 3, of type `int', y = 2, of type `int'
x = 3, of type `int', y = 3, of type `int'
But this is Nim, you can do Anything (TM) :D
iterator pairs(r: array[0 .. 1, HSlice[system.int, system.int]]): tuple[a: int, b: int] =
for r1 in r[0]:
for r2 in r[1]:
yield (r1, r2)
for x, y in [0 .. 3, 0 .. 3]:
echo x, " ", y
Outputs:
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
2 3
3 0
3 1
3 2
3 3
but i got lost on the way