Data structures: vector and map, stack, queue, deque, set, linked list, priority queue and counter.
import collections
This package holds Salam's data structures. Vector and HashMap, which turn up in every program, are defined here but built in: you can use them without an import. The rest (Stack, Queue, Deque, Set, Counter, PriorityQueue, OrderedMap, LinkedList, CircularList, Pair) and the vector helpers such as clone and IndexOf need import collections. To sort or search a vector use sort; to share a structure between threads, guard it with sync, because none of these types locks.
All of them are generic: you set the element type with <...>, as in collections.Stack<str>, and build an empty one with collections.Stack {} as collections.Stack<str>. All of them allocate, so write defer x.Free() right after creating one. Free releases the structure itself, not heap strings or other objects stored in it.
Which should you pick? For an ordinary list, Vector; for "last in, first out", Stack; for "first in, first out", Queue; for adding and removing at both ends, Deque; for fast lookup by a key, HashMap; for removing duplicates, Set; for "always give me the smallest", PriorityQueue; and for string settings that must keep their order, OrderedMap. Most of them are thin layers over Vector: a stack is one vector, a queue and a deque are two.
What people get wrong:
•
Copying with =. b := a moves the vector to b, and using a afterwards is an error (E259); with two names sharing one buffer a push on one could move the memory under the other. Take a real copy with the built-in v.copy() or with collections.clone(v). The same goes for a HashMap (m.copy()) and for any struct holding one.
•
Changing a struct you got from a map. m.Get(k) returns a copy; change it and Put it back.
•
Reading from an empty structure. pop, peek, dequeue, first, last and an index past the end stop the program with a message such as Vector.pop: empty. Check IsEmpty() first. A --release build leaves the check out, and the same mistake then reads garbage.
•
Printing a map in its own order. each key, value in m visits the slots in hash order, which changes as the map grows. Collect and sort the keys when the order shows.
Vector: insert, remove, copy
push and pop work at the end in constant time. Insert and RemoveAt shift every later element, so they are fine for short lists and slow inside a loop over a long one. IndexOf and contains scan from the front. The example also shows what a copy is for: changing line does not reach the clone, which keeps its own elements.
collections-guide-vector.salam
import collections
funcmain:
mut line := Vector {} asVector<str>
defer line.Free()
each name in ["Ali", "Sara", "Reza"]:
line.Push(name)
end
line.Insert(1, "Mina")
println"after insert:", line
served := line.RemoveAt(0)
println"served", served, "->", line
println"Reza is at",
collections.IndexOf(line, "Reza"),
"and Omid at",
collections.IndexOf(line, "Omid")
backup := collections.Clone(line)
defer backup.Free()
line.Set(0, "Neda")
println"line changed:", line.Get(0)
println"the clone kept:", backup.Get(0)
front := collections.Slice(line, 0, 2)
defer front.Free()
println"first two:", front, "last:", line.Last()
end
Output
after insert: ["Ali", "Mina", "Sara", "Reza"]
served Ali -> ["Mina", "Sara", "Reza"]
Reza is at 2 and Omid at -1
line changed: Neda
the clone kept: Mina
first two: ["Neda", "Sara"] last: Reza
slice returns a new vector and clamps a range that runs past the end, so it never fails. Printing a vector with println shows its elements, which is handy while debugging.
HashMap: stock by product code
A HashMap finds a value by its key in constant time. Get on a missing key returns the zero value of the type (0, empty text, a struct of zeros) and never fails, so ask Has first when a missing key is an error, or use GetOr when a default is right. Struct values come back as copies: change the copy and Put it again.
collections-guide-inventory.salam
import sort
structStock:
pub name: str = ""pub qty: int = 0endfuncmain:
mut stock := HashMap {} asHashMap<str, Stock>
defer stock.Free()
stock.Put("TEA-01", Stock { name = "Green tea", qty = 40 })
stock.Put("COF-02", Stock { name = "Coffee beans", qty = 12 })
stock.Put("MUG-07", Stock { name = "Mug", qty = 2 })
each sku in ["COF-02", "MUG-07", "TEA-01", "MUG-07", "BAG-99"]:
ifnot stock.Has(sku):
println"unknown product", sku
continueendmut item := stock.Get(sku)
item.qty--
stock.Put(sku, item)
endprintln"a missing key gives a zero value:", stock.Get("BAG-99").qty
mut reorder_at := HashMap {} asHashMap<str, int>
defer reorder_at.Free()
reorder_at.Put("TEA-01", 10)
mut skus := Vector {} asVector<str>
defer skus.Free()
each sku, item in stock:
if item.qty > 0:
skus.Push(sku)
else:
println item.name, "is sold out"endend
sort.Sort(skus)
each sku in skus:
item := stock.Get(sku)
low := item.qty <= reorder_at.GetOr(sku, 5)
println sku, item.name, item.qty, "reorder:", low
endend
Output
unknown product BAG-99
a missing key gives a zero value: 0
Mug is sold out
COF-02 Coffee beans 11 reorder: false
TEA-01 Green tea 39 reorder: false
Do not Put or Remove while an each loop walks the same map: a Put can grow the table and move every entry. Collect the keys first, as the example does, then change the map.
Stack: matching brackets
A stack is the tool when the most recent thing must be dealt with first. Checking brackets is the classic case: push every opening bracket, and on a closing bracket the top of the stack must be its partner. peek looks at the top without removing it, and whatever is left at the end was never closed.
collections-guide-brackets.salam
import collections
importstrfuncopener(c: char): char:
if c == ')': ret '(' endif c == ']': ret '[' endret '{'
endfunccheck(s: str): str:
mut open := collections.Stack {} as collections.Stack<char>
defer open.Free()
repeatstr.Len(s) in i:
c := s[i]
if c == '(' or c == '[' or c == '{':
open.Push(c)
else c == ')' or c == ']' or c == '}':
if open.IsEmpty() or open.Peek() != opener(c):
ret"mismatch at " + str.FromInt(i)
end
open.Pop()
endendifnot open.IsEmpty():
retstr.FromInt(open.Size()) + " left open"endret"balanced"endfuncmain:
each s in ["f(a[1], {b: 2})", "(1 + 2]", "{[()]}", "((x)", "x)"]:
println s, "->", check(s)
endend
Output
f(a[1], {b: 2}) -> balanced
(1 + 2] -> mismatch at 6
{[()]} -> balanced
((x) -> 1 left open
x) -> mismatch at 1
Queue: shortest path in a grid
A queue hands items out in the order they arrived, which is exactly what a breadth first search needs: every cell at distance 1 is handled before any cell at distance 2, so the first time the search reaches the exit, it has found a shortest path. enqueue adds at the back and dequeue takes from the front.
collections-guide-maze.salam
import collections
funcmain:
maze := ["S.#.....", ".##.###.", "....#...", ".##...#E"]
rows := maze.Len()
cols := 8
dr := [-1, 1, 0, 0]
dc := [0, 0, -1, 1]
mut dist := Vector {} asVector<int>
defer dist.Free()
repeat rows * cols:
dist.Push(-1)
endmut todo := collections.Queue {} as collections.Queue<int>
defer todo.Free()
todo.Enqueue(0)
dist.Set(0, 0)
mut goal := -1untilnot todo.IsEmpty():
cell := todo.Dequeue()
r := cell / cols
c := cell % cols
if maze[r][c] == 'E':
goal = cell
breakendrepeat4in k:
nr := r + dr[k]
nc := c + dc[k]
if nr >= 0and nr < rows and nc >= 0and nc < cols:
next := nr * cols + nc
if maze[nr][nc] != '#' and dist.Get(next) == -1:
dist.Set(next, dist.Get(cell) + 1)
todo.Enqueue(next)
endendendendprintln"shortest path to E:", dist.Get(goal), "steps"mut seen := 0each d in dist:
if d >= 0: seen++ endendprintln"cells reached:", seen, "of", rows * cols
end
Output
shortest path to E: 12 steps
cells reached: 22 of 32
Deque and Stack together: undo with a limit
An undo history adds at one end and, once it is full, drops the oldest step at the other end, so it needs a Deque. Undone steps go onto a Stack for redo, and any new edit clears that stack, as editors do.
collections-guide-history.salam
import collections
funcmain:
limit := 3mut undo := collections.Deque {} as collections.Deque<str>
defer undo.Free()
mut redo := collections.Stack {} as collections.Stack<str>
defer redo.Free()
mut doc := ""each word in ["Salam", " is", " a", " small", " language"]:
undo.PushBack(doc)
if undo.Size() > limit:
undo.PopFront()
end
redo.Clear()
doc += word
println"typed: [" + doc + "]"enduntilnot undo.IsEmpty():
redo.Push(doc)
doc = undo.PopBack()
println"undo: [" + doc + "]"endprintln"the history keeps only", limit, "steps, so the rest are gone"
doc = redo.Pop()
println"redo: [" + doc + "]", redo.Size(), "more redo steps"end
Output
typed: [Salam]
typed: [Salam is]
typed: [Salam is a]
typed: [Salam is a small]
typed: [Salam is a small language]
undo: [Salam is a small]
undo: [Salam is a]
undo: [Salam is]
the history keeps only 3 steps, so the rest are gone
redo: [Salam is a] 2 more redo steps
Counter and Set: counting words
Counter keeps a count for each value it has seen; count answers 0 for a value it never saw, so no check is needed first. A Set answers "have I seen this?" quickly and here keeps the words in order of first use. A stable sort by count then keeps that order among words with the same count.
collections-guide-wordcount.salam
import collections
import sort
importstrfuncmain:
text := "to be or not to be that is the question to ask"mut counts := collections.Counter {} as collections.Counter<str>
defer counts.Free()
mut seen := collections.Set {} as collections.Set<str>
defer seen.Free()
mut order := Vector {} asVector<str>
defer order.Free()
each w instr.Fields(text):
counts.Add(w)
ifnot seen.Has(w):
seen.Add(w)
order.Push(w)
endendprintln counts.Distinct(), "different words, in order of first use:"println order
sort.StableSortBy(order, (a: str, b: str): ret counts.Count(a) > counts.Count(b) end)
println"most frequent:"repeat3in i:
w := order.Get(i)
println" " + w, counts.Count(w)
endend
Output
9 different words, in order of first use:
["to", "be", "or", "not", "that", "is", "the", "question", "ask"]
most frequent:
to 3
be 2
or 1
PriorityQueue: the most urgent job first
PriorityQueue is a binary min-heap: push and pop take log n steps, and pop always returns the smallest element. It compares elements with <, so it holds numbers or strings, not structs. To queue records, pack the priority and a position into one number, here urgency * 1000 + index, and keep the records in a vector. The position also breaks ties in arrival order, which a heap would not do by itself. For the largest first, push negative numbers.
collections-guide-scheduler.salam
import collections
funcmain:
jobs := [
"nightly backup", "send invoices", "resize images", "page the on-call", "rebuild index"
]
urgency := [3, 2, 3, 1, 2]
mut queue := collections.PriorityQueue {} as collections.PriorityQueue<i64>
defer queue.Free()
repeat jobs.Len() in i:
queue.Push((urgency[i] asi64) * 1000 + (i asi64))
enduntilnot queue.IsEmpty():
key := queue.Pop()
println"urgency", key / 1000, jobs[(key % 1000) asint]
endmut largest := collections.PriorityQueue {} as collections.PriorityQueue<int>
defer largest.Free()
each kb in [120, 4800, 35, 990]:
largest.Push(-kb)
endprintln"largest upload first:", -largest.Pop(), "KB, then", -largest.Peek(), "KB"end
Output
urgency 1 page the on-call
urgency 2 send invoices
urgency 2 rebuild index
urgency 3 nightly backup
urgency 3 resize images
largest upload first: 4800 KB, then 990 KB
OrderedMap: settings that keep their order
A HashMap gives its keys back in no particular order, which is a nuisance when you write a configuration file back to disk. OrderedMap keeps keys in the order they were first set; changing a value keeps its position, and Set returns that position. GetOr supplies a default for a missing key.
collections-guide-config.salam
import collections
importstrfuncmain:
mut conf := collections.OrderedMap {}
defer conf.Free()
conf.Set("host", "127.0.0.1")
conf.Set("port", "8080")
conf.Set("workers", "4")
conf.Set("log", "info")
overrides := ["port=9000", "log=debug", "tls=on", "broken"]
each line in overrides:
cut := str.IndexOf(line, "=")
if cut < 0:
println"skipping", line
continueend
key := line.Substr(0, cut)
value := line.Substr(cut + 1, str.Len(line) - cut - 1)
known := conf.Has(key)
pos := conf.Set(key, value)
if known:
println"changed", key, "at position", pos
else:
println"added", key, "at position", pos
endend
conf.Remove("workers")
repeat conf.Len() in i:
println conf.KeyAt(i) + " = " + conf.ValAt(i)
endprintln"timeout:", conf.GetOr("timeout", "30")
end
Output
changed port at position 1
changed log at position 3
added tls at position 4
skipping broken
host = 127.0.0.1
port = 9000
log = debug
tls = on
timeout: 30
You need
Use
Main methods
Last in, first out
Stack
push, pop, peek
First in, first out
Queue
enqueue, dequeue
Both ends
Deque
PushBack, PopFront, PopBack
How often each value appears
Counter
add, count, distinct
Each value once
Set
add, Has
A list by position
Vector
push, Get, Insert, RemoveAt
A value by key
HashMap
Put, Has, GetOr, Remove
The smallest first
PriorityQueue
push, pop, peek
Taking turns in a circle
CircularList
current, advance
String settings in a fixed order
OrderedMap
Set, GetOr, KeyAt, ValAt
Every one of these types allocates. Put defer x.Free() on the line after you create it, as the examples do, and the memory is released when the function returns. Set and Counter have no way to list their contents; when you need that, walk their inner map with each value, _ in s.m, or keep a vector beside them as the word count example does.
A counter: it counts how many times it has seen each thing, such as the words in a text. To list the counts, walk c.m.
Name
Type
Description
m
HashMap<K, int>
A map from each thing to its count.
collections-Counter.salam
import collections
importstrfuncmain:
mut c := collections.Counter {} as collections.Counter<str>
defer c.Free()
each word instr.Fields("in the name of the friend"):
c.Add(word)
end
c.AddN("friend", 2)
println c.Count("the"), c.Count("friend"), c.Count("missing"), c.Distinct()
end
Returns an iterator over each distinct key and its count. The order is not defined.
collections-CounterIter.salam
import collections
importstrfuncmain:
mut c := collections.Counter {} as collections.Counter<str>
defer c.Free()
each word instr.Fields("in the name of the friend the"):
c.Add(word)
endmut total := 0mut it := c.Iter()
until it.HasNext():
if it.Key() == "the":
println it.Key(), it.Value()
end
total += it.Value()
it.Next()
endprintln total, c.Distinct()
end
A set: each element only once. For removing duplicates and asking "is this one there?" quickly. It is a HashMap to bool underneath and has no iterator of its own; walk s.m to list the elements.
Name
Type
Description
m
HashMap<T, bool>
The map that holds the elements as keys.
collections-Set.salam
import collections
funcmain:
mut s := collections.Set {} as collections.Set<str>
defer s.Free()
each word in ["hello", "world", "hello"]:
s.Add(word)
endprintln s.Size(), s.Has("hello"), s.Has("goodbye")
println s.Remove("world"), s.Size(), s.IsEmpty()
end
Returns an iterator over the members. The order is not defined.
collections-SetIter.salam
import collections
funcmain:
mut s := collections.Set {} as collections.Set<str>
defer s.Free()
each word in ["hello", "world", "hello"]:
s.Add(word)
endmut seen := 0mut it := s.Iter()
until it.HasNext():
if s.Has(it.Value()):
seen++
end
it.Next()
endprintln seen, s.Size()
end
A list whose size changes: the data structure you will use most. The elements sit next to each other in memory and access by index is immediate. You can also read and write elements with [i].
Name
Type
Description
data
T*
The address of the elements in memory.
collections-Vector.salam
funcmain:
mut v := Vector {} asVector<int>
defer v.Free()
v.Reserve(8)
println v.Len(), v.Cap() >= 8, v.IsEmpty()
v.Push(10)
v.Push(20)
v.Push(30)
println v, v.First(), v.Last(), v.Get(1), v[2]
v.Set(0, 11)
v[1] = 22
v.Insert(1, 15)
println v
println v.RemoveAt(1), v.Pop(), v
r := v.Ref(0)
r[0] = 99println v
v.ResizeSet(v.Len(), 7)
println v
v.Clear()
println v.Len()
mut z := Vector {} asVector<int>
defer z.Free()
z.Zeros(3)
println z
mut a := Vector {} asVector<int>
defer a.Free()
a.Alloc(4)
println a.Len()
end
Like Set, but grows the vector when i is past the end. The slots between the old length and i have no defined value, so either fill them in order or start with zeros.
A double-ended queue: you can add and remove at either end. It is two vectors; when one end runs dry it takes every element from the other, so a large deque that keeps alternating PopFront and PopBack copies all its elements each time.
Name
Type
Description
front
Vector<T>
The elements at the front end.
back
Vector<T>
The elements at the back end.
collections-Deque.salam
import collections
funcmain:
mut d := collections.Deque {} as collections.Deque<int>
defer d.Free()
d.PushBack(2)
d.PushBack(3)
d.PushFront(1)
println d.FrontVal(), d.BackVal(), d.Get(1), d.Size()
println d.PopFront(), d.PopBack(), d.Size(), d.IsEmpty()
end
A priority queue: the smallest element comes out each time, whatever order they went in. A binary min-heap compared with <, so the elements must be numbers or strings; push negative numbers for the largest first. For scheduling work and for shortest path algorithms.
Name
Type
Description
h
Vector<T>
The elements as a binary heap.
collections-PriorityQueue.salam
import collections
funcmain:
mut q := collections.PriorityQueue {} as collections.PriorityQueue<int>
defer q.Free()
each n in [5, 1, 4, 2, 3]:
q.Push(n)
endprintln q.Peek(), q.Size()
untilnot q.IsEmpty():
print q.Pop(), ""endprintln""end
A map from key to value with fast lookup, like a dictionary, using open addressing. The order of the entries is not predictable and changes as the map grows; if the insertion order matters, see OrderedMap. Built in, no import needed.
Name
Type
Description
keys
K*
The address of the array of keys.
vals
V*
The address of the array of values.
state
i8*
The state of each slot: empty, filled or removed.
cap
int = 0
The number of slots.
count
int = 0
The number of keys present.
used
int = 0
The number of slots in use, removed ones included.
Returns the value for a key. When the key is absent you get the zero value of the type, so ask with Has first or use GetOr. A struct value is a copy; Put it back after changing it.
A queue: the first element in is the first one out, like a queue at a shop. Built from two vectors, so each element is moved once and every operation is constant time on average.
Name
Type
Description
inbox
Vector<T>
The newly arrived elements.
outbox
Vector<T>
The elements ready to leave; whenever it empties it is refilled from inbox.