Arrays

An array is collection of value of the same type. An array can be expressed using a literal.

let a = [1, 2, 3]; // an array of int of size 3
let b = a ~ [4]; // Array concatenation

// assert ensure that the test is true and exit the program otherwise
assert (b.len == 4); 

println ("First element of b : ", b [0]);
println ("Last element of b : ", b [$ - 1]); // here $ will take the value of b.len

Array are iterable types.

let a = [8, 4, 2];
for i in a {
    println (i); // 8, 4, 2
    i = 12;
}
assert (a == [12, 12, 12]);

You can borrow a section of an array using slicing. This borrowing is done by reference.

import std.algorithm.sorting;

let a = [3, 4, 2, 1];
let b = a [0 .. 2]; 

assert (b == [3, 4]);

a [2 .. $].sort (fn (a, b) => a < b); // Lambda function a detailed later
// Here we are sorting the array a from index 2 to index 4 
assert (a == [3, 4, 1, 2]);