Lists
Also known as: array vector arraylist slice append index element push pop collection sequence
● Beginner5 minBefore this: For Loop, VariablesSpec 2.2
A list holds many values of one type, in order, under one name: ["mango", "fig"].
fn main() {
let fruits = ["mango", "fig"]
fruits.push("yuzu")
print(fruits)
print(fruits[0])
print(fruits.len())
for fruit in fruits {
print(fruit.upper())
}
}The program ran and printed:
kavach run overview.kav
["mango", "fig", "yuzu"]mango3MANGOFIGYUZU
- Square brackets make a list. Its type is written
[String]: a list of strings. fruits[0]is the first item: positions start at 0.pushadds to the end. It changes the list, so the list must be alet.
All the items of a list have the same type. To group values of different types, use a tuple or a record.
One page for each form
Try it yourself
Show the answer
let xs = [1, 2, 3], then xs.push(4) and print(xs.len()): 4.
Go deeper the why, for readers who want it
Two things make Kavach lists fast. Values never alias: a list always has one owner, so the compiler can keep it in registers and skip defensive copies. And lists of small items are packed, so more items fit in each cache line:
| What | Limit or size | Source |
|---|---|---|
[UInt8], [Int8], [Bool] | 1 byte per item | 0030-byte-packed-lists.md |
[Int16], [UInt16]; [Int32], [UInt32], [Float32] | 2 bytes; 4 bytes per item | 0045-packed-lists-of-small-numbers.md |
Other items | 8 bytes per item: a 64-bit number, or a reference to a bigger value. Packing is in native code; the interpreter keeps its own values | 0045-packed-lists-of-small-numbers.md |
Every limit in Kavach, on one page: Limits and Sizes.
lists — build, read, change and sum 10M items · WSL Ubuntu 24.04 · i7-13700HX · kavach build (LLVM) · g++ 13 -O2 · Go 1.23 · .NET 8 (C# start-up included) · best of 9
git clone https://github.com/Mithlesh04/kavach && cd kavach
sh scripts/run-benchmarks.sh "" benchmarks/loops