Learn/Nim/7. Collections
Lesson 7 of 8
Sign in

Nim, lesson 7

Collections

Programs rarely work with one value at a time. Nim's everyday collections are the array (fixed size), the seq (a list that can grow) and the Table (a dictionary).

Arrays and seqs

An array has a length fixed when you compile. A seq (sequence) can grow and shrink while the program runs. You write a seq with @ in front of the brackets:

Every item must have the same type. Nim checks indexes at runtime, so scores[10] stops the program with a clear error instead of reading garbage. An empty seq of ints is written newSeq[int]() or declared with var xs: seq[int].

Looping is the same as for ranges, and pairs gives you the index too:

Helpful procedures

The standard library covers the common jobs. min, max and are always available; others live in modules you import:

2 exercises to try what you just read.

Exercise 1

Score stats

Press Ctrl Enter or Check to test your code.

Exercise 2

Vote tally

Press Ctrl Enter or Check to test your code.

len

std/[math, algorithm, sequtils] imports three modules in one line. In filterIt and mapIt, the name it stands for the current item.

Tables

A Table maps keys to values:

Reading a missing key with stock["kiwi"] raises a KeyError, so check with in or use getOrDefault first. For counting, mgetOrPut is perfect: it returns the stored value (adding a starting value first if the key is new) in a form you can change in place:

A Table does not keep keys in any useful order. To print them sorted, collect the keys into a seq with toSeq(counts.keys) and sort that.

From a line of text to a seq

splitWhitespace (from strutils) breaks a string on runs of spaces: "4 8 15" becomes @["4", "8", "15"]. Then .map(parseInt) converts every piece.

Further reading

  • Nim Tutorial (Part I): arrays and sequences
  • The tables module
  • The sequtils module and the algorithm module

Read a line of game scores separated by spaces and print four statistics.

Input: one line with at least one whole number. Output:

That is for the input 12 6 21 3.

A class votes for the name of its pet fish. Count the votes for each name.

Input: the first line is the number of votes N (0 or more). Then N lines follow, each with one name (a single word).

Output: one line per name, name: votes, sorted alphabetically by name. If there are no votes, print No votes.

prints

let podium = ["gold", "silver", "bronze"]   # array of 3 strings
var scores = @[72, 95, 88]                  # seq[int]

scores.add(60)          # @[72, 95, 88, 60]
echo scores.len         # 4
echo scores[0]          # 72 (indexes start at 0)
echo scores[^1]         # 60 (^1 means "last")
for i, s in scores.pairs:
  echo i, ": ", s
import std/[math, algorithm, sequtils]

echo scores.max                  # 95
echo scores.sum                  # 315 (from math)
echo scores.sorted               # @[60, 72, 88, 95] (from algorithm)
echo scores.filterIt(it >= 80)   # @[95, 88] (from sequtils)
echo scores.mapIt(it + 5)        # @[77, 100, 93, 65]
import std/tables

var stock = {"apple": 3, "pear": 0}.toTable
stock["plum"] = 7                   # add or replace
echo stock["apple"]                 # 3
echo stock.getOrDefault("kiwi", 0)  # 0 for a missing key
echo "pear" in stock                # true
var counts = initTable[string, int]()
for drink in ["tea", "coffee", "tea"]:
  counts.mgetOrPut(drink, 0) += 1
Count: 4
Min: 3
Max: 21
Sum: 42
4
Bubbles
Finn
Bubbles
Nemo
Bubbles: 2
Finn: 1
Nemo: 1