Skip to content
Kavachकवच

Sorting: Numbers

● Beginner3 min

Numbers sort smallest first, exactly: NaN goes last, and Decimal and BigInt sort by their full value.

fn main() {
    print([42, -7, 0, 1_000, 3].sort())
    const sizes: [UInt8] = [200, 3, 77]
    print(sizes.sort())
    print([10, 2, 33].sort().reverse())
}

The program ran and printed:

kavach run numbers.kav

[-7, 0, 3, 42, 1000][3, 77, 200][33, 10, 2]
numbers.kav: Kavach code, then what running it prints
fn main() {
    const nan = 0.0 / 0.0
    print([2.5, nan, -1.0, 0.1 + 0.2, 0.3].sort())
    print([0.0, -0.0, -1.5].sort())
}

The program ran and printed:

kavach run floats.kav

[-1.0, 0.3, 0.3, 2.5, NaN][-1.5, 0.0, 0.0]
floats.kav: Kavach code, then what running it prints
  • NaN (not a number) sorts after every number, so a list holding one still sorts.
  • 0.1 + 0.2 is exactly 0.3 in Kavach, so it sorts as equal to 0.3.
  • 0.0 and -0.0 are equal, and keep their order.
fn main() {
    const prices: [Decimal] = [19.99, 5.00, 19.90]
    print(prices.sort())
    const big = [BigInt(2) ** 100, BigInt(-5), BigInt(10) ** 30]
    print(big.sort())
}

The program ran and printed:

kavach run exact.kav

[5.00, 19.90, 19.99][-5, 1000000000000000000000000000000, 1267650600228229401496703205376]
exact.kav: Kavach code, then what running it prints