Skip to content

Instantly share code, notes, and snippets.

@tonetheman
Created December 18, 2022 17:43
Show Gist options
  • Save tonetheman/2c1b5f9d3b421c5f44daf5acb601fc4a to your computer and use it in GitHub Desktop.
Save tonetheman/2c1b5f9d3b421c5f44daf5acb601fc4a to your computer and use it in GitHub Desktop.
2d seq and some array examples for nim
# see here also for seq
# https://nimbyexample.com/sequences.html
# pretty print a seq
# or better than just echo it
proc pp(a: seq[ seq[int] ] ) =
for i in a:
echo(i)
proc part1() =
# make the row dim first
var a = newSeq[ seq[int] ](5)
# shows the 5 rows allocated and usable
echo("first version of a only row has been allocated")
echo(a)
# assign a new seq to the first row
a[0] = newSeq[int](5)
# shows like it should
echo("2nd version of a first row has a seq[int] assigned and usable")
echo(a)
echo("setting a[0][1] to 200")
a[0][1] = 200
# pretty print an array
echo("pretty print the array")
pp(a)
# allocate all of the rows
# leaked some memory on the first row
for i in 0 ..< 5:
a[i] = newSeq[int](5)
echo("pretty print all rows assigned leaked a row!")
pp(a)
proc part2() =
# declare an empty seq
var a : seq[ seq[int ]]
echo(a)
# add a single line
a.add( newSeq[int](5) )
pp(a)
# add 4 more lines
for i in 0 ..< 4:
a.add( newSeq[int](5) )
pp(a)
# seq is variable len so add a long seq on the end
a.add( newSeq[int](7))
pp(a)
proc part3() =
# if you know the size
# then use an array
var a : array[ 5, array[5,int] ]
for i in a:
echo(i)
part3()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment