Nim, lesson 7
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).
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:
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.
lenstd/[math, algorithm, sequtils] imports three modules in one line. In filterIt and mapIt,
the name it stands for the current item.
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.
splitWhitespace (from strutils) breaks a string on runs of spaces: "4 8 15" becomes
@["4", "8", "15"]. Then .map(parseInt) converts every piece.
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, ": ", simport 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 # truevar counts = initTable[string, int]()
for drink in ["tea", "coffee", "tea"]:
counts.mgetOrPut(drink, 0) += 1Count: 4
Min: 3
Max: 21
Sum: 424
Bubbles
Finn
Bubbles
NemoBubbles: 2
Finn: 1
Nemo: 1