I am brand new to Nim and am bumping into some issues. The following code results in SIGSEGV: Illegal storage access. (Attempt to read from nil?)
. I can't seem to figure out how to populate a sequence of sequences with values.
const
a = @[ 0, 1, 2, 3, 4, 5]
b = @[10, 11, 12, 13, 14, 15]
var
matrix: seq[seq[int]]
for i, aa in a:
for j, bb in b:
matrix[i][j] = aa+bb
Other approaches I've attempted seem to be closer...
var
matrix = newSeq[seq[int]]()
for i, aa in a:
var row = newSeq[int]()
for j, bb in b:
row[i] = aa+bb
matrix[i] = row
...but now I'm hitting out of bounds [IndexError]
...
var
matrix = newSeq[seq[int]](5)
for i, aa in a:
var row = newSeq[int](5)
for j, bb in b:
row[i] = aa+bb
matrix[i] = row
...what am I doing wrong?
Advertisements. Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.
seq -s “STRING” FIRST INCREMENT LAST: This command is uses to STRING to separate numbers. By default this value is equal to “ ”. FIRST and INCREMENT are optional. Recommended: Please try your approach on {IDE} first, before moving on to the solution. seq -w FIRST INCREMENT LAST: This command is used to equalize width by padding with leading zeroes.
On Linux, you can find several commands with unusual functionalities. One such command is seq, which outputs a sequence of numbers depending on the arguments specified. But what can you possibly do with a command-line utility that throws a bunch of digits at you? You'll find out in this guide. What Is the seq Command?
When you only specify one number, seq interprets it as the upper limit for the list and generates a sequence starting from one up to the number specified. The aforementioned command will output the following: When seq receives two numbers as the input, it interprets them as the lower limit and upper limit for the sequence.
Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.
If you don't want to resize the seq, an easier solution is to preallocate it:
import sequtils
const
a = @[ 0, 1, 2, 3, 4, 5]
b = @[10, 11, 12, 13, 14, 15]
var matrix = newSeqWith(a.len, newSeq[int](b.len))
for i, aa in a:
for j, bb in b:
matrix[i][j] = aa + bb
echo matrix
Success!
It turns out, Nim really doesn't like you using square brackets in places where data doesn't exist yet. That is matrix[i] = item
will blow up. However, matrix.add(item)
will work well.
Here is how I ended up creating a 2D array in Nim:
var
matrix: seq[seq[int]]
row: seq[int]
matrix = newSeq[seq[int]]()
for i, aa in a:
row = newSeq[int]()
matrix.add(row)
for j, bb in b:
matrix[i].add(aa+bb)
echo matrix
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With