|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching • Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
SequencesA sequence is a dynamic array. Same thing as a list in Python. Sequences are stored on the heap, thus they are garbage collected.
When you simply write In the Nim code, var nums = @[] # ERROR: cannot infer the type 𝥶It doesn't work because the compiler cannot figure out the type of the sequence. var nums = @[1, 2, 3] # OK 𝥶It's OK, var numbers1: seq[int] 𝥶Here we declare a sequence of integers. Nim will initialize it, thus it becomes an empty sequence. echo numbers1.len 𝥶This if UFCS. It's actually transformed to Set the capacityIf you know a priori how many elements you want to store in a seq, then you can set its capacity to avoid reallocations. var li = newSeqOfCap[int](10_000) echo len(li) # 0 li.add(5) li.add(8) echo len(li) # 2 Now, in this list you can insert 10,000 elements and you can be sure that no reallocations will happen. When you want to insert the 10,001st element, then the list will grow itself to make room for the new element. A common dynamic array growth strategy is to double the capacity, so at the 10,001st element the capacity would jump to ~20,000. Set the lengthIf you know a priori how many elements you want to store in a seq, then you can set its length to avoid reallocations. However! This time the sequence will be filled with zeroed entries! After the creation of the sequence, you should assign entries to the sequence (using the indexes) instead of adding them! var li = newSeq[int](10) echo li # @[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] echo len(li) # 10 li[0] = 1 li[1] = 2 echo li # @[1, 2, 0, 0, 0, 0, 0, 0, 0, 0] li.add(99) echo li # @[1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 99] |
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |
||||