Standard library · Numbers and collections

collections

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

func main:
    mut line := Vector {} as Vector<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

struct Stock:
    pub name: str = ""
    pub qty: int = 0
end

func main:
    mut stock := HashMap {} as HashMap<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"]:
        if not stock.Has(sku):
            println "unknown product", sku
            continue
        end
        mut item := stock.Get(sku)
        item.qty--
        stock.Put(sku, item)
    end
    println "a missing key gives a zero value:", stock.Get("BAG-99").qty

    mut reorder_at := HashMap {} as HashMap<str, int>
    defer reorder_at.Free()
    reorder_at.Put("TEA-01", 10)

    mut skus := Vector {} as Vector<str>
    defer skus.Free()
    each sku, item in stock:
        if item.qty > 0:
            skus.Push(sku)
        else:
            println item.name, "is sold out"
        end
    end
    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
    end
end
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
import str

func opener(c: char): char:
    if c == ')': ret '(' end
    if c == ']': ret '[' end
    ret '{'
end

func check(s: str): str:
    mut open := collections.Stack {} as collections.Stack<char>
    defer open.Free()
    repeat str.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()
        end
    end
    if not open.IsEmpty():
        ret str.FromInt(open.Size()) + " left open"
    end
    ret "balanced"
end

func main:
    each s in ["f(a[1], {b: 2})", "(1 + 2]", "{[()]}", "((x)", "x)"]:
        println s, "->", check(s)
    end
end
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

func main:
    maze := ["S.#.....", ".##.###.", "....#...", ".##...#E"]
    rows := maze.Len()
    cols := 8
    dr := [-1, 1, 0, 0]
    dc := [0, 0, -1, 1]
    mut dist := Vector {} as Vector<int>
    defer dist.Free()
    repeat rows * cols:
        dist.Push(-1)
    end

    mut todo := collections.Queue {} as collections.Queue<int>
    defer todo.Free()
    todo.Enqueue(0)
    dist.Set(0, 0)
    mut goal := -1
    until not todo.IsEmpty():
        cell := todo.Dequeue()
        r := cell / cols
        c := cell % cols
        if maze[r][c] == 'E':
            goal = cell
            break
        end
        repeat 4 in k:
            nr := r + dr[k]
            nc := c + dc[k]
            if nr >= 0 and nr < rows and nc >= 0 and 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)
                end
            end
        end
    end
    println "shortest path to E:", dist.Get(goal), "steps"
    mut seen := 0
    each d in dist:
        if d >= 0: seen++ end
    end
    println "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

func main:
    limit := 3
    mut 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 + "]"
    end

    until not undo.IsEmpty():
        redo.Push(doc)
        doc = undo.PopBack()
        println "undo:  [" + doc + "]"
    end
    println "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
import str

func main:
    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 {} as Vector<str>
    defer order.Free()

    each w in str.Fields(text):
        counts.Add(w)
        if not seen.Has(w):
            seen.Add(w)
            order.Push(w)
        end
    end
    println 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:"
    repeat 3 in i:
        w := order.Get(i)
        println "  " + w, counts.Count(w)
    end
end
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

func main:
    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] as i64) * 1000 + (i as i64))
    end
    until not queue.IsEmpty():
        key := queue.Pop()
        println "urgency", key / 1000, jobs[(key % 1000) as int]
    end

    mut largest := collections.PriorityQueue {} as collections.PriorityQueue<int>
    defer largest.Free()
    each kb in [120, 4800, 35, 990]:
        largest.Push(-kb)
    end
    println "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
import str

func main:
    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
            continue
        end
        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
        end
    end

    conf.Remove("workers")
    repeat conf.Len() in i:
        println conf.KeyAt(i) + " = " + conf.ValAt(i)
    end
    println "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 needUseMain methods
Last in, first outStackpush, pop, peek
First in, first outQueueenqueue, dequeue
Both endsDequePushBack, PopFront, PopBack
How often each value appearsCounteradd, count, distinct
Each value onceSetadd, Has
A list by positionVectorpush, Get, Insert, RemoveAt
A value by keyHashMapPut, Has, GetOr, Remove
The smallest firstPriorityQueuepush, pop, peek
Taking turns in a circleCircularListcurrent, advance
String settings in a fixed orderOrderedMapSet, 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.

Types

Counter

#
struct Counter<K>

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.

NameTypeDescription
mHashMap<K, int>A map from each thing to its count.
collections-Counter.salam
import collections
import str

func main:
    mut c := collections.Counter {} as collections.Counter<str>
    defer c.Free()
    each word in str.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
Output
2 3 0 5

Add

#
func Add(k: K)

AddN

#
func AddN(k: K, n: int)

Count

#
func Count(k: K): int

Total

#
func Total(): int

Distinct

#
func Distinct(): int

Iter

#
func Iter(): CounterIter<K>

Returns an iterator over each distinct key and its count. The order is not defined.

collections-CounterIter.salam
import collections
import str

func main:
    mut c := collections.Counter {} as collections.Counter<str>
    defer c.Free()
    each word in str.Fields("in the name of the friend the"):
        c.Add(word)
    end
    mut total := 0
    mut it := c.Iter()
    until it.HasNext():
        if it.Key() == "the":
            println it.Key(), it.Value()
        end
        total += it.Value()
        it.Next()
    end
    println total, c.Distinct()
end
Output
the 3
7 5

CounterIter

#
struct CounterIter<K>

A counter iterator; walk with HasNext, key, value and next.

NameTypeDescription
innerMapIter<K, int>The map iterator underneath.

The example for this item is shown with the ones above: collections-CounterIter.salam

Value

#
func Value(): int

How many times the current key was counted.

The example for this item is shown with the ones above: collections-CounterIter.salam

OrderedMap

#
struct OrderedMap

A map from string to string that keeps the insertion order, for headers, settings and anywhere the display order matters.

NameTypeDescription
keysVector<str>The keys in insertion order.
valsVector<str>The values in the same order.
idxHashMap<str, int>A map from key to its position, for fast lookup.
collections-OrderedMap.salam
import collections

func main:
    mut m := collections.OrderedMap {}
    defer m.Free()
    m.Set("name", "Salam")
    m.Set("version", "0.5.0")
    m.Set("language", "english")
    println m.Len(), m.Has("version"), m.Get("name"), m.GetOr("licence", "-")
    println m.IndexOf("language"), m.KeyAt(0), m.ValAt(0)
    m.SetAt(0, "Salam")
    println m.Remove("version"), m.Len()
    keys := m.CloneKeys()
    println keys
end
Output
3 true Salam -
2 name Salam
1 2
["name", "language"]

IndexOf

#
func IndexOf(k: str): int

Returns the position of a key, or minus one.

The example for this item is shown with the ones above: collections-OrderedMap.salam

Get

#
func Get(k: str): str

The value for a key, or an empty string when it is absent.

The example for this item is shown with the ones above: collections-OrderedMap.salam

GetOr

#
func GetOr(k: str, def: str): str

The value for a key, or the default.

The example for this item is shown with the ones above: collections-OrderedMap.salam

Set

#
func Set(k: str, v: str): int

Stores the value for a key; a new key goes on the end and an existing key keeps its place. It returns the key's position.

The example for this item is shown with the ones above: collections-OrderedMap.salam

KeyAt

#
func KeyAt(i: int): str

Key number i, or empty text when i is out of range.

The example for this item is shown with the ones above: collections-OrderedMap.salam

ValAt

#
func ValAt(i: int): str

Value number i, or empty text when i is out of range.

The example for this item is shown with the ones above: collections-OrderedMap.salam

SetAt

#
func SetAt(i: int, v: str)

Remove

#
func Remove(k: str): int

Removes a key and returns the position it had, or minus one. Every later key moves back one place, so it takes longer on a long map.

The example for this item is shown with the ones above: collections-OrderedMap.salam

CloneKeys

#
func CloneKeys(): Vector<str>

Iter

#
func Iter(): OrderedMapIter

Returns an iterator over the entries in insertion order.

collections-OrderedMapIter.salam
import collections

func main:
    mut m := collections.OrderedMap {}
    defer m.Free()
    m.Set("name", "Salam")
    m.Set("version", "0.5.0")
    m.Set("language", "english")
    mut it := m.Iter()
    until it.HasNext():
        println it.Key(), it.Value()
        it.Next()
    end
end
Output
name Salam
version 0.5.0
language english

OrderedMapIter

#
struct OrderedMapIter

An ordered map iterator; walk with HasNext, key, value and next.

NameTypeDescription
keysVector<str>The keys in order.
valsVector<str>The values in order.
posint = 0The current position.

The example for this item is shown with the ones above: collections-OrderedMapIter.salam

Stack

#
struct Stack<T>

A stack: the last element added is the first one taken off, like a pile of books.

NameTypeDescription
itemsVector<T>The elements of the stack; the last one is the top.
collections-Stack.salam
import collections

func main:
    mut s := collections.Stack {} as collections.Stack<str>
    defer s.Free()
    s.Push("book 1")
    s.Push("book 2")
    s.Push("book 3")
    println s.Peek(), s.Size()
    println s.Pop(), s.Pop(), s.Size()
    s.Clear()
    println s.IsEmpty()
end
Output
book 3 3
book 3 book 2 1
true

Push

#
func Push(x: T)

Puts an element on the stack.

The example for this item is shown with the ones above: collections-Stack.salam

Pop

#
func Pop(): T

Takes the top element off and returns it; an empty stack stops the program.

The example for this item is shown with the ones above: collections-Stack.salam

Peek

#
func Peek(): T

Size

#
func Size(): int

The number of elements.

The example for this item is shown with the ones above: collections-Stack.salam

IsEmpty

#
func IsEmpty(): bool

True when the stack is empty.

The example for this item is shown with the ones above: collections-Stack.salam

Clear

#
func Clear()

Iter

#
func Iter(): StackIter<T>

Returns an iterator over the stack from the bottom to the top. each ... in on items does the same.

collections-StackIter.salam
import collections

func main:
    mut s := collections.Stack {} as collections.Stack<str>
    defer s.Free()
    s.Push("book 1")
    s.Push("book 2")
    s.Push("book 3")
    mut it := s.Iter()
    until it.HasNext():
        println it.Value()
        it.Next()
    end
end
Output
book 1
book 2
book 3

Free

#
func Free()

Releases the stack's memory.

The example for this item is shown with the ones above: collections-Stack.salam

StackIter

#
struct StackIter<T>

A stack iterator; walk with HasNext, value and next.

NameTypeDescription
itemsVector<T>The stack's elements, bottom first.
posint = 0The current position.

The example for this item is shown with the ones above: collections-StackIter.salam

HasNext

#
func HasNext(): bool

True when another element is left.

The example for this item is shown with the ones above: collections-StackIter.salam

Set

#
struct Set<T>

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.

NameTypeDescription
mHashMap<T, bool>The map that holds the elements as keys.
collections-Set.salam
import collections

func main:
    mut s := collections.Set {} as collections.Set<str>
    defer s.Free()
    each word in ["hello", "world", "hello"]:
        s.Add(word)
    end
    println s.Size(), s.Has("hello"), s.Has("goodbye")
    println s.Remove("world"), s.Size(), s.IsEmpty()
end
Output
2 true false
true 1 false

Add

#
func Add(x: T)

Has

#
func Has(x: T): bool

True when the element is in the set.

The example for this item is shown with the ones above: collections-Set.salam

Remove

#
func Remove(x: T): bool

Removes an element, and returns false when it was not there.

The example for this item is shown with the ones above: collections-Set.salam

Size

#
func Size(): int

The number of elements.

The example for this item is shown with the ones above: collections-Set.salam

IsEmpty

#
func IsEmpty(): bool

True when it is empty.

The example for this item is shown with the ones above: collections-Set.salam

Iter

#
func Iter(): SetIter<T>

Returns an iterator over the members. The order is not defined.

collections-SetIter.salam
import collections

func main:
    mut s := collections.Set {} as collections.Set<str>
    defer s.Free()
    each word in ["hello", "world", "hello"]:
        s.Add(word)
    end
    mut seen := 0
    mut it := s.Iter()
    until it.HasNext():
        if s.Has(it.Value()):
            seen++
        end
        it.Next()
    end
    println seen, s.Size()
end
Output
2 2

Free

#
func Free()

Releases the memory.

The example for this item is shown with the ones above: collections-Set.salam

SetIter

#
struct SetIter<T>

A set iterator; walk with HasNext, value and next.

NameTypeDescription
innerMapIter<T, bool>The map iterator underneath.

The example for this item is shown with the ones above: collections-SetIter.salam

HasNext

#
func HasNext(): bool

True when another member is left.

The example for this item is shown with the ones above: collections-SetIter.salam

Vector

#
struct Vector<T>

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].

NameTypeDescription
dataT*The address of the elements in memory.
collections-Vector.salam
func main:
    mut v := Vector {} as Vector<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] = 99
    println v
    v.ResizeSet(v.Len(), 7)
    println v
    v.Clear()
    println v.Len()
    mut z := Vector {} as Vector<int>
    defer z.Free()
    z.Zeros(3)
    println z
    mut a := Vector {} as Vector<int>
    defer a.Free()
    a.Alloc(4)
    println a.Len()
end
Output
0 true true
[10, 20, 30] 10 30 20 30
[11, 15, 22, 30]
15 30 [11, 22]
[99, 22]
[99, 22, 7]
0
[0, 0, 0]
4

Reserve

#
func Reserve(need: int)

Reserves room for at least need elements in advance, so that later additions do not move the memory again.

The example for this item is shown with the ones above: collections-Vector.salam

Push

#
func Push(x: T)

Adds an element at the end.

The example for this item is shown with the ones above: collections-Vector.salam

Pop

#
func Pop(): T

Removes the last element and returns it. On an empty vector it stops the program.

The example for this item is shown with the ones above: collections-Vector.salam

Get

#
func Get(i: int): T

Returns element number i. An index outside 0 to len()-1 stops the program (the check is left out of --release builds).

The example for this item is shown with the ones above: collections-Vector.salam

Ref

#
func Ref(i: int): T*

Returns the address of element number i, so you can change it in place without a copy.

The example for this item is shown with the ones above: collections-Vector.salam

Set

#
func Set(i: int, x: T)

Replaces element number i, which must already exist; use push to add.

The example for this item is shown with the ones above: collections-Vector.salam

ResizeSet

#
func ResizeSet(i: int, x: T)

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.

The example for this item is shown with the ones above: collections-Vector.salam

Zeros

#
func Zeros(n: int)

Replaces the contents with n zero elements; anything already in the vector is dropped.

The example for this item is shown with the ones above: collections-Vector.salam

Alloc

#
func Alloc(n: int)

Replaces the contents with n uninitialised elements, dropping what was there; fill them before reading.

The example for this item is shown with the ones above: collections-Vector.salam

Cap

#
func Cap(): int

The current capacity: how many more elements fit before new memory is taken.

The example for this item is shown with the ones above: collections-Vector.salam

IsEmpty

#
func IsEmpty(): bool

True when the vector has no elements.

The example for this item is shown with the ones above: collections-Vector.salam

First

#
func First(): T

The first element; an empty vector stops the program.

The example for this item is shown with the ones above: collections-Vector.salam

Last

#
func Last(): T

The last element; an empty vector stops the program.

The example for this item is shown with the ones above: collections-Vector.salam

Clear

#
func Clear()

Removes every element but keeps the memory.

The example for this item is shown with the ones above: collections-Vector.salam

Insert

#
func Insert(i: int, x: T)

Inserts an element at position i (0 to len()) and shifts the rest forward, so it takes longer the more elements follow.

The example for this item is shown with the ones above: collections-Vector.salam

RemoveAt

#
func RemoveAt(i: int): T

Removes and returns the element at position i and shifts the rest back.

The example for this item is shown with the ones above: collections-Vector.salam

operator_index

#
func operator_index(i: int): T

The same as reading with v[i].

The example for this item is shown with the ones above: collections-Vector.salam

operator_index_set

#
func operator_index_set(i: int, x: T)

The same as writing with v[i] = x.

The example for this item is shown with the ones above: collections-Vector.salam

Iter

#
func Iter(): VectorIter<T>

Returns an iterator for walking the elements by hand. Most of the time each ... in is simpler.

collections-VectorIter.salam
func main:
    mut v := Vector {} as Vector<str>
    defer v.Free()
    v.Push("spring")
    v.Push("summer")
    mut it := v.Iter()
    until it.HasNext():
        println it.Value()
        it.Next()
    end
end
Output
spring
summer

Free

#
func Free()

Releases the vector's memory and leaves it empty and usable. Elements that own memory, such as strings from str functions, are not freed.

The example for this item is shown with the ones above: collections-Vector.salam

VectorIter

#
struct VectorIter<T>

A vector iterator; walk element by element with HasNext, value and next.

NameTypeDescription
dataT*The address of the vector's elements.
lenint = 0
posint = 0The current position.

The example for this item is shown with the ones above: collections-VectorIter.salam

HasNext

#
func HasNext(): bool

True when another element is left.

The example for this item is shown with the ones above: collections-VectorIter.salam

Pair

#
struct Pair<A, B>

A pair of values, for returning two things from a function or keeping a key and a value together.

NameTypeDescription
firstAThe first value.
secondBThe second value.
collections-Pair.salam
import collections

func main:
    p := collections.Pair {
        first = "Tehran", second = 8700000
    } as collections.Pair<str, int>
    println p.first, p.second
end
Output
Tehran 8700000

Deque

#
struct Deque<T>

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.

NameTypeDescription
frontVector<T>The elements at the front end.
backVector<T>The elements at the back end.
collections-Deque.salam
import collections

func main:
    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
Output
1 3 2 3
1 3 1 false

PushFront

#
func PushFront(x: T)

Adds an element at the front.

The example for this item is shown with the ones above: collections-Deque.salam

PushBack

#
func PushBack(x: T)

Adds an element at the back.

The example for this item is shown with the ones above: collections-Deque.salam

PopFront

#
func PopFront(): T

Removes the front element and returns it; an empty deque stops the program.

The example for this item is shown with the ones above: collections-Deque.salam

PopBack

#
func PopBack(): T

Removes the back element and returns it; an empty deque stops the program.

The example for this item is shown with the ones above: collections-Deque.salam

Front

#
func Front(): T

FrontVal

#
func FrontVal(): T

Shows the front element without removing it.

The example for this item is shown with the ones above: collections-Deque.salam

Back

#
func Back(): T

BackVal

#
func BackVal(): T

Shows the back element without removing it.

The example for this item is shown with the ones above: collections-Deque.salam

Size

#
func Size(): int

The number of elements.

The example for this item is shown with the ones above: collections-Deque.salam

IsEmpty

#
func IsEmpty(): bool

True when it is empty.

The example for this item is shown with the ones above: collections-Deque.salam

Get

#
func Get(i: int): T

Element number i counted from the front.

The example for this item is shown with the ones above: collections-Deque.salam

LinkedList

#
struct LinkedList<T>

A doubly linked list; adding and removing at either end is fast.

NameTypeDescription
valsVector<T>The values of the nodes.
nxtVector<int>The index of each node's next node.
prvVector<int>The index of each node's previous node.
headintThe index of the first node.
tailintThe index of the last node.
freedintThe index of the first freed node, kept for reuse.
countint = 0The number of elements.
collections-LinkedList.salam
import collections

func main:
    mut l := collections.LinkedList {} as collections.LinkedList<str>
    defer l.Free()
    l.PushBack("b")
    l.PushBack("c")
    l.PushFront("a")
    println l.ToVector(), l.Size()
    println l.FrontVal(), l.BackVal(), l.Get(1)
    println l.PopFront(), l.PopBack(), l.Size(), l.IsEmpty()
end
Output
["a", "b", "c"] 3
a c b
a c 1 false

PopFront

#
func PopFront(): T

Removes the front element and returns it.

The example for this item is shown with the ones above: collections-LinkedList.salam

PopBack

#
func PopBack(): T

Removes the last element and returns it.

The example for this item is shown with the ones above: collections-LinkedList.salam

Get

#
func Get(i: int): T

Element number i from the front. Reaching it means walking from the front, so for repeated access by index a vector is better.

The example for this item is shown with the ones above: collections-LinkedList.salam

ToVector

#
func ToVector(): Vector<T>

Returns the elements, in order, in a new vector.

The example for this item is shown with the ones above: collections-LinkedList.salam

PriorityQueue

#
struct PriorityQueue<T>

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.

NameTypeDescription
hVector<T>The elements as a binary heap.
collections-PriorityQueue.salam
import collections

func main:
    mut q := collections.PriorityQueue {} as collections.PriorityQueue<int>
    defer q.Free()
    each n in [5, 1, 4, 2, 3]:
        q.Push(n)
    end
    println q.Peek(), q.Size()
    until not q.IsEmpty():
        print q.Pop(), ""
    end
    println ""
end
Output
1 5
1 2 3 4 5

Peek

#
func Peek(): T

Pop

#
func Pop(): T

Removes the smallest element and returns it; an empty queue stops the program. Equal elements come out in no particular order.

The example for this item is shown with the ones above: collections-PriorityQueue.salam

HashMap

#
struct HashMap<K, V>

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.

NameTypeDescription
keysK*The address of the array of keys.
valsV*The address of the array of values.
statei8*The state of each slot: empty, filled or removed.
capint = 0The number of slots.
countint = 0The number of keys present.
usedint = 0The number of slots in use, removed ones included.
collections-HashMap.salam
func main:
    mut m := HashMap {} as HashMap<str, int>
    defer m.Free()
    println m.IsEmpty()
    m.Put("apple", 3)
    m.Insert("pear", 5)
    m.Put("apple", 4)
    println m.Size(), m.Has("apple"), m.Get("apple"), m.GetOr("banana", 0)
    println m.Remove("pear"), m.Remove("pear"), m.Size()
    mut it := m.Iter()
    until it.HasNext():
        println it.Key(), it.Value()
        it.Next()
    end
end
Output
true
2 true 4 0
true false 1
apple 4

Put

#
func Put(k: K, v: V)

Stores the value for a key, replacing an earlier value for the same key.

The example for this item is shown with the ones above: collections-HashMap.salam

Has

#
func Has(k: K): bool

True when the key is in the map.

The example for this item is shown with the ones above: collections-HashMap.salam

Get

#
func Get(k: K): V

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.

The example for this item is shown with the ones above: collections-HashMap.salam

GetOr

#
func GetOr(k: K, def: V): V

Returns the value for a key, or the default when it is absent.

The example for this item is shown with the ones above: collections-HashMap.salam

Remove

#
func Remove(k: K): bool

Removes a key, and returns false when it was not there.

The example for this item is shown with the ones above: collections-HashMap.salam

IsEmpty

#
func IsEmpty(): bool

True when the map is empty.

The example for this item is shown with the ones above: collections-HashMap.salam

Iter

#
func Iter(): MapIter<K, V>

Returns an iterator over the keys and values. Most of the time each key, value in is simpler.

The example for this item is shown with the ones above: collections-HashMap.salam

Free

#
func Free()

Releases the map's memory; keys and values that own memory are not freed.

The example for this item is shown with the ones above: collections-HashMap.salam

MapIter

#
struct MapIter<K, V>

A map iterator.

NameTypeDescription
keysK*The address of the array of keys.
valsV*The address of the array of values.
statei8*The state of the slots.
capint = 0The number of slots.
posint = 0The current position.

The example for this item is shown with the ones above: collections-HashMap.salam

HasNext

#
func HasNext(): bool

True when another entry is left.

The example for this item is shown with the ones above: collections-HashMap.salam

CircularList

#
struct CircularList<T>

A circular list: after the last element you come back to the first, for taking turns in rotation, such as the players in a game.

NameTypeDescription
itemsVector<T>The elements in the order they were added.
offsetint = 0
collections-CircularList.salam
import collections

func main:
    mut c := collections.CircularList {} as collections.CircularList<str>
    defer c.Free()
    each name in ["Ali", "Sara", "Reza"]:
        c.Add(name)
    end
    repeat 4:
        print c.Current(), ""
        c.Advance()
    end
    println ""
    c.Rotate(1)
    println c.ToVector(), c.Get(0), c.Size(), c.IsEmpty()
end
Output
Ali Sara Reza Ali 
["Reza", "Ali", "Sara"] Reza 3 false

Add

#
func Add(x: T)

Get

#
func Get(i: int): T

The element i places on from the current one; a negative number is accepted.

The example for this item is shown with the ones above: collections-CircularList.salam

Rotate

#
func Rotate(k: int)

Current

#
func Current(): T

Advance

#
func Advance()

ToVector

#
func ToVector(): Vector<T>

Returns the elements from the current one onward, in a new vector.

The example for this item is shown with the ones above: collections-CircularList.salam

Queue

#
struct Queue<T>

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.

NameTypeDescription
inboxVector<T>The newly arrived elements.
outboxVector<T>The elements ready to leave; whenever it empties it is refilled from inbox.
collections-Queue.salam
import collections

func main:
    mut q := collections.Queue {} as collections.Queue<str>
    defer q.Free()
    q.Enqueue("customer 1")
    q.Enqueue("customer 2")
    q.Enqueue("customer 3")
    println q.Peek(), q.Size()
    println q.Dequeue(), q.Dequeue(), q.IsEmpty()
end
Output
customer 1 3
customer 1 customer 2 false

Enqueue

#
func Enqueue(x: T)

Dequeue

#
func Dequeue(): T

Peek

#
func Peek(): T

Size

#
func Size(): int

The number of elements.

The example for this item is shown with the ones above: collections-Queue.salam

IsEmpty

#
func IsEmpty(): bool

True when the queue is empty.

The example for this item is shown with the ones above: collections-Queue.salam

Iter

#
func Iter(): QueueIter<T>

Returns an iterator over the queue from the front to the back, without removing anything.

collections-QueueIter.salam
import collections

func main:
    mut q := collections.Queue {} as collections.Queue<str>
    defer q.Free()
    q.Enqueue("customer 1")
    q.Enqueue("customer 2")
    q.Enqueue("customer 3")
    println q.Dequeue()
    q.Enqueue("customer 4")
    mut it := q.Iter()
    until it.HasNext():
        println it.Value()
        it.Next()
    end
end
Output
customer 1
customer 2
customer 3
customer 4

Free

#
func Free()

Releases the queue's memory.

The example for this item is shown with the ones above: collections-Queue.salam

QueueIter

#
struct QueueIter<T>

A queue iterator; walk with HasNext, value and next.

NameTypeDescription
outboxVector<T>The front part of the queue, as the iterator saw it.
inboxVector<T>The back part of the queue, as the iterator saw it.
posint = 0The current position.

The example for this item is shown with the ones above: collections-QueueIter.salam

HasNext

#
func HasNext(): bool

True when another element is left.

The example for this item is shown with the ones above: collections-QueueIter.salam

Functions

Contains

#
func Contains<T>(v: Vector<T>, x: T): bool

IndexOf

#
func IndexOf<T>(v: Vector<T>, x: T): int

The position of the first occurrence of x, or minus one.

collections-Funcs.salam
import collections

func main:
    mut a := Vector {} as Vector<int>
    defer a.Free()
    each n in [1, 2, 3, 2, 5]:
        a.Push(n)
    end
    println collections.Contains(a, 3),
        collections.IndexOf(a, 2),
        collections.LastIndexOf(a, 2),
        collections.CountOf(a, 2)
    println collections.Reverse(a), collections.Slice(a, 1, 3)
    b := collections.Clone(a)
    collections.Swap(a, 0, 4)
    println a, b
    mut c := Vector {} as Vector<int>
    defer c.Free()
    collections.Extend(c, b)
    collections.Extend(c, b)
    println c.Len()
end
Output
true 1 3 2
[5, 2, 3, 2, 1] [2, 3, 2]
[5, 2, 3, 2, 1] [1, 2, 3, 2, 5]
10

Reverse

#
func Reverse<T>(v: Vector<T>): Vector<T>

Clone

#
func Clone<T>(v: Vector<T>): Vector<T>

Slice

#
func Slice<T>(v: Vector<T>, start: int, count: int): Vector<T>

Swap

#
func Swap<T>(v: Vector<T>, i: int, j: int)

CountOf

#
func CountOf<T>(v: Vector<T>, x: T): int

LastIndexOf

#
func LastIndexOf<T>(v: Vector<T>, x: T): int

Extend

#
func Extend<T>(dst &: Vector<T>, src: Vector<T>)