Skip to content
Kavachकवच

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
overview.kav: Kavach code, then what running it prints
  • Square brackets make a list. Its type is written [String]: a list of strings.
  • fruits[0] is the first item: positions start at 0.
  • push adds to the end. It changes the list, so the list must be a let.

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

Make a list of three numbers, add a fourth, and print how many there are.
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:

WhatLimit or sizeSource
[UInt8], [Int8], [Bool]1 byte per item0030-byte-packed-lists.md
[Int16], [UInt16]; [Int32], [UInt32], [Float32]2 bytes; 4 bytes per item0045-packed-lists-of-small-numbers.md
Other items8 bytes per item: a 64-bit number, or a reference to a bigger value. Packing is in native code; the interpreter keeps its own values0045-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

Kavach32 ms · finished 1st
C++ -O273 ms · 2.3× behind
Go124 ms · 3.9× behind
C#211 ms · 6.6× behind
Verify itgit clone https://github.com/Mithlesh04/kavach && cd kavach sh scripts/run-benchmarks.sh "" benchmarks/loops