Arrays, Sequences, Open Arrays and Slices
9.1 Arrays (Fixed Size, Stack Allocated)
var a: array[5, int] # [0, 0, 0, 0, 0]
let b = [1, 2, 3] # array[3, int]
var grid: array[3, array[3, char]]
type Week = array[Monday..Sunday, string] # indexed by an enum range
echo b.len, b.low, b.high9.2 Sequences (Dynamic, Heap Allocated)
var s = @[1, 2, 3] # seq[int]
var empty: seq[string]
var pre = newSeq[int](10) # 10 zeroed elements
var cap = newSeqOfCap[int](100)
s.add(4); s.add([5, 6])
s.insert(0, 0)
s.delete(1) # remove index 1 (shifts)
s.del(0) # O(1) swap-remove (order not kept)
echo s.pop(), s.len, s.contains(3), 3 in s, s.find(3)
s.setLen(2)
echo s & @[9, 9]9.3 Slices and Backwards Indices
let nums = @[10, 20, 30, 40, 50]
echo nums[1..3] # @[20, 30, 40]
echo nums[^2] # 40
echo nums[2..^1] # @[30, 40, 50]
var t = nums
t[0..1] = @[1, 2]9.4 Open Arrays
openArray[T] parameters accept arrays, seqs, and slices without copying:
proc total(xs: openArray[int]): int =
for x in xs: result += x
echo total([1, 2, 3]), total(@[4, 5]), total(nums.toOpenArray(1, 3))9.5 std/sequtils and std/algorithm
import std/[sequtils, algorithm, sugar]
let xs = @[5, 3, 8, 1]
echo xs.map(x => x * 2)
echo xs.filter(x => x > 2)
echo xs.foldl(a + b)
echo xs.mapIt(it * it) # *It templates use the implicit `it`
echo xs.filterIt(it mod 2 == 1)
echo xs.anyIt(it > 7), xs.allIt(it > 0), xs.countIt(it > 2)
echo toSeq(1..5), xs.deduplicate, xs.zip(@["a", "b", "c", "d"])
echo xs.sorted, xs.sorted(SortOrder.Descending), xs.sortedByIt(-it)
var ys = xs; ys.sort(); ys.reverse()
echo ys.binarySearch(5), xs.max, xs.min, xs.sum # sum from std/math
echo collect(for x in xs: (if x > 2: x * 10)) # sugar.collect: comprehension