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 copies only the vector's header, so both names see the same elements: b.Set(0, x) changes a too, and a push on one can 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 is_empty() 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 remove_at 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 the copy trap from the list above: alias writes straight into line, while the clone 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()
    alias := line
    alias.Set(0, "Neda")
    println "alias wrote into line:", 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
Outputafter insert: ["Ali", "Mina", "Sara", "Reza"] served Ali -> ["Mina", "Sara", "Reza"] Reza is at 2 and Omid at -1 alias wrote into line: 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
Outputunknown 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
Outputf(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
Outputshortest 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
Outputtyped: [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
Output9 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(0 - kb)
    end
    println "largest upload first:", 0 - largest.Pop(), "KB, then", 0 - largest.Peek(), "KB"
end
Outputurgency 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
Outputchanged 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 endsDequepush_back, pop_front, pop_back
How often each value appearsCounteradd, count, distinct
Each value onceSetadd, Has
A list by positionVectorpush, Get, Insert, remove_at
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

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 pop_front and pop_back copies all its elements each time.
NameTypeDescription
frontVectorThe elements at the front end.
backVectorThe 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
Output1 3 2 3 1 3 1 false

PushFront

func PushFront(x: T)

push_front

func push_front(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)

push_back

func push_back(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

pop_front

func pop_front(): 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

pop_back

func pop_back(): 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

front_val

func front_val(): T
Shows the front element without removing it.

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

FrontVal

func FrontVal(): T

Back

func Back(): T

back_val

func back_val(): T
Shows the back element without removing it.

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

BackVal

func BackVal(): T

Size

func Size(): int
The number of elements.

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

size

func size(): int

IsEmpty

func IsEmpty(): bool
True when it is empty.

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

is_empty

func is_empty(): bool

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

get

func get(i: int): T

Free

func Free()
Releases the memory.

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

free

func free()

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
Outputtrue 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

put

func put(k: K, v: V)

Insert

func Insert(k: K, v: V)
The same as Put.

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

insert

func insert(k: K, v: V)

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

has

func has(k: K): bool

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

get

func get(k: K): V

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

get_or

func get_or(k: K, def: V): V

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

remove

func remove(k: K): bool

Size

func Size(): int
The number of keys.

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

size

func size(): int

IsEmpty

func IsEmpty(): bool
True when the map is empty.

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

is_empty

func is_empty(): bool

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

iter

func iter(): MapIter<K, V>

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

free

func free()

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

has_next

func has_next(): bool

Key

func Key(): K

key

func key(): K
The current key.

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

Value

func Value(): V

value

func value(): V
The current value.

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

Next

func Next()

next

func next()
Moves to the next entry.

The example for this item is shown with the ones above: collections-HashMap.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
OutputTehran 8700000

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
itemsVectorThe 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
OutputAli Sara Reza Ali ["Reza", "Ali", "Sara"] Reza 3 false

Add

func Add(x: T)

add

func add(x: T)
Adds an element to the list.

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

Size

func Size(): int
The number of elements.

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

size

func size(): int

IsEmpty

func IsEmpty(): bool
True when it is empty.

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

is_empty

func is_empty(): bool

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

get

func get(i: int): T

Rotate

func Rotate(k: int)

rotate

func rotate(k: int)
Moves the current element on by k places, or back with a negative number.

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

Current

func Current(): T

current

func current(): T
The current element: whose turn is it?

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

Advance

func Advance()

advance

func advance()
Passes the turn to the next element.

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

ToVector

func ToVector(): Vector<T>

to_vector

func to_vector(): 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

Free

func Free()
Releases the memory.

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

free

func free()

Stack

struct Stack<T>
A stack: the last element added is the first one taken off, like a pile of books.
NameTypeDescription
itemsVectorThe 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
Outputbook 3 3 book 3 book 2 1 true

Push

func Push(x: T)

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

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

peek

func peek(): T
Shows the top element without taking it off; an empty stack stops the program.

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

Size

func Size(): int
The number of elements.

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

size

func size(): int

IsEmpty

func IsEmpty(): bool
True when the stack is empty.

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

is_empty

func is_empty(): bool

Clear

func Clear()

clear

func clear()
Takes every element off.

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

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
Outputbook 1 book 2 book 3

iter

func iter(): StackIter<T>

Free

func Free()
Releases the stack's memory.

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

free

func free()

StackIter

struct StackIter<T>
A stack iterator; walk with HasNext, value and next.
NameTypeDescription
itemsVectorThe 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

has_next

func has_next(): bool

Value

func Value(): T

value

func value(): T
The current element.

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

Next

func Next()

next

func next()
Moves to the next element.

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
mHashMapThe 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
Output2 true false true 1 false

Add

func Add(x: T)

add

func add(x: T)
Adds an element; if it is already there, nothing happens.

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

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

has

func has(x: T): bool

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

remove

func remove(x: T): bool

Size

func Size(): int
The number of elements.

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

size

func size(): int

IsEmpty

func IsEmpty(): bool
True when it is empty.

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

is_empty

func is_empty(): bool

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
Output2 2

iter

func iter(): SetIter<T>

Free

func Free()
Releases the memory.

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

free

func free()

SetIter

struct SetIter<T>
A set iterator; walk with HasNext, value and next.
NameTypeDescription
innerMapIterThe 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

has_next

func has_next(): bool

Value

func Value(): T

value

func value(): T
The current member.

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

Next

func Next()

next

func next()
Moves to the next member.

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

LinkedList

struct LinkedList<T>
A doubly linked list; adding and removing at either end is fast.
NameTypeDescription
valsVectorThe values of the nodes.
nxtVectorThe index of each node's next node.
prvVectorThe 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

push_back

func push_back(v: T)
Adds an element at the end.

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

PushBack

func PushBack(v: T)

push_front

func push_front(v: T)
Adds an element at the front.

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

PushFront

func PushFront(v: T)

pop_front

func pop_front(): T
Removes the front element and returns it.

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

PopFront

func PopFront(): T

pop_back

func pop_back(): T
Removes the last element and returns it.

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

PopBack

func PopBack(): T

FrontVal

func FrontVal(): T

front_val

func front_val(): T
The front element.

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

BackVal

func BackVal(): T

back_val

func back_val(): T
The last element.

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

size

func size(): int

Size

func Size(): int
The number of elements.

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

is_empty

func is_empty(): bool

IsEmpty

func IsEmpty(): bool
True when it is empty.

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

get

func get(i: int): T

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

to_vector

func to_vector(): 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

ToVector

func ToVector(): Vector<T>

free

func free()

Free

func Free()
Releases the memory.

The example for this item is shown with the ones above: collections-LinkedList.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
keysVectorThe keys in insertion order.
valsVectorThe values in the same order.
idxHashMapA 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
Output3 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

index_of

func index_of(k: str): int

Len

func Len(): int
The number of keys.

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

len

func len(): int

Has

func Has(k: str): bool
True when the key is there.

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

has

func has(k: str): bool

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

get

func get(k: str): str

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

get_or

func get_or(k: str, def: str): str

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

set

func set(k: str, v: str): int

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

key_at

func key_at(i: int): str

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

val_at

func val_at(i: int): str

SetAt

func SetAt(i: int, v: str)

set_at

func set_at(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

remove

func remove(k: str): int

CloneKeys

func CloneKeys(): Vector<str>

clone_keys

func clone_keys(): Vector<str>
A copy of the keys in insertion order.

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

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
Outputname Salam version 0.5.0 language english

iter

func iter(): OrderedMapIter

Free

func Free()
Releases the memory.

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

free

func free()

OrderedMapIter

struct OrderedMapIter
An ordered map iterator; walk with HasNext, key, value and next.
NameTypeDescription
keysVectorThe keys in order.
valsVectorThe values in order.
posint = 0The current position.

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

HasNext

func HasNext(): bool
True when another entry is left.

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

has_next

func has_next(): bool

Key

func Key(): str

key

func key(): str
The current key.

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

Value

func Value(): str

value

func value(): str
The current value.

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

Next

func Next()

next

func next()
Moves to the next entry.

The example for this item is shown with the ones above: collections-OrderedMapIter.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
hVectorThe 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
Output1 5 1 2 3 4 5

Push

func Push(x: T)

push

func push(x: T)
Adds an element.

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

Peek

func Peek(): T

peek

func peek(): T
Shows the smallest element without removing it; an empty queue stops the program.

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

Pop

func Pop(): 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

Size

func Size(): int
The number of elements.

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

size

func size(): int

IsEmpty

func IsEmpty(): bool
True when it is empty.

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

is_empty

func is_empty(): bool

Free

func Free()
Releases the memory.

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

free

func free()

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
inboxVectorThe newly arrived elements.
outboxVectorThe 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
Outputcustomer 1 3 customer 1 customer 2 false

Enqueue

func Enqueue(x: T)

enqueue

func enqueue(x: T)
Adds an element at the back of the queue.

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

Dequeue

func Dequeue(): T

dequeue

func dequeue(): T
Takes the element at the front out; an empty queue stops the program.

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

Peek

func Peek(): T

peek

func peek(): T
Shows the element at the front without taking it out.

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

Size

func Size(): int
The number of elements.

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

size

func size(): int

IsEmpty

func IsEmpty(): bool
True when the queue is empty.

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

is_empty

func is_empty(): bool

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
Outputcustomer 1 customer 2 customer 3 customer 4

iter

func iter(): QueueIter<T>

Free

func Free()
Releases the queue's memory.

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

free

func free()

QueueIter

struct QueueIter<T>
A queue iterator; walk with HasNext, value and next.
NameTypeDescription
outboxVectorThe front part of the queue, as the iterator saw it.
inboxVectorThe 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

has_next

func has_next(): bool

Value

func Value(): T

value

func value(): T
The current element.

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

Next

func Next()

next

func next()
Moves to the next element.

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

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
mHashMapA 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.add_n("friend", 2)
    println c.count("the"), c.count("friend"), c.count("missing"), c.distinct()
end
Output2 3 0 5

Add

func Add(k: K)

add

func add(k: K)
Adds one to the count of k.

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

Count

func Count(k: K): int

count

func count(k: K): int
How many times k has been seen, or zero if never.

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

Total

func Total(): int

total

func total(): int

Distinct

func Distinct(): int

distinct

func distinct(): int
The number of different things counted.

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

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
Outputthe 3 7 5

iter

func iter(): CounterIter<K>

Free

func Free()
Releases the memory.

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

free

func free()

CounterIter

struct CounterIter<K>
A counter iterator; walk with HasNext, key, value and next.
NameTypeDescription
innerMapIterThe map iterator underneath.

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

HasNext

func HasNext(): bool
True when another key is left.

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

has_next

func has_next(): bool

Key

func Key(): K

key

func key(): K
The current key.

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

Value

func Value(): int

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

Next

func Next()

next

func next()
Moves to the next key.

The example for this item is shown with the ones above: collections-CounterIter.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.resize_set(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
Output0 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

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)

resize_set

func resize_set(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

len

func len(): int

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

is_empty

func is_empty(): bool

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)

remove_at

func remove_at(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>

free

func free()

Reserve

func Reserve(need: int)

Push

func Push(x: T)

Pop

func Pop(): T

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*

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)

Zeros

func Zeros(n: int)

Alloc

func Alloc(n: int)

Len

func Len(): int
The number of elements.

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

Cap

func Cap(): int

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

Last

func Last(): T

Clear

func Clear()

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

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
Outputspring 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

has_next

func has_next(): bool

value

func value(): T
The current element.

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

next

func next()
Moves to the next element.

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

Value

func Value(): T

Next

func Next()

Functions

Contains

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

contains

func contains<T>(v: Vector<T>, x: T): bool
True when x is in the vector.
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
Outputtrue 1 3 2 [5, 2, 3, 2, 1] [2, 3, 2] [5, 2, 3, 2, 1] [1, 2, 3, 2, 5] 10

IndexOf

func IndexOf<T>(v: Vector<T>, x: T): int
The position of the first occurrence of x, or minus one.

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

index_of

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

Reverse

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

reverse

func reverse<T>(v: Vector<T>): Vector<T>
A reversed copy of the vector; the original is unchanged. Free the copy.

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

Clone

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

clone

func clone<T>(v: Vector<T>): Vector<T>
An independent copy of the vector, the way to copy one: plain assignment shares the elements.

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

Slice

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

slice

func slice<T>(v: Vector<T>, start: int, count: int): Vector<T>
A new vector of up to count elements starting at start; a range past the end is cut short instead of failing.

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

Swap

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

swap

func swap<T>(v: Vector<T>, i: int, j: int)
Exchanges two elements.

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

CountOf

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

count_of

func count_of<T>(v: Vector<T>, x: T): int
How many times x occurs in the vector.

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

LastIndexOf

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

last_index_of

func last_index_of<T>(v: Vector<T>, x: T): int
The position of the last occurrence of x, or minus one.

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

Extend

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

extend

func extend<T>(dst &: Vector<T>, src: Vector<T>)
Adds every element of src to the end of dst; dst is passed by reference.

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