Hare by Example: Slices

Slices are similar to arrays in most ways except that they can store an arbitrary number of elements. They are allowed to grow and shrink as as well.

use fmt;

export fn main() void = {
	// Slices do still need to be intialized, but their size is
	// dynamic.
	let slice: []int = [];
	fmt::print("Empty: ")!;
	print(slice);

	// We can append elements to slices using the built-in `append`
	// function. `append` will mutate the slice directly.
	append(slice, 99)!;
	fmt::print("Append single: ")!;
	print(slice);

	// We append multiple elements using the ... operator which the
	// `append` function accepts.
	append(slice, [11, 22, 33]...)!;
	fmt::print("Append multiple: ")!;
	print(slice);

	// You can create new slices from existing ones and specify the
	// starting and ending indicies for the new slices.
	let head = slice[..2];
	let tail = slice[2..];
	let mid = slice[2..3];

	fmt::print("Head: ")!;
	print(head);

	fmt::print("Tail: ")!;
	print(tail);

	fmt::print("Mid: ")!;
	print(mid);

	// We can even insert elements at specific places into a slice.
	insert(slice[3], 88)!;
	fmt::print("Insert: ")!;
	print(slice);

	// We can also delete elements from a slice, both single
	// elements or a range of elements.
	delete(slice[3]);
	fmt::print("Delete single: ")!;
	print(slice);

	delete(slice[2..4]);
	fmt::print("Delete multiple: ")!;
	print(slice);

	// You can also create slices from array since a slice is just a
	// view into an underlying array anyway.
	let array: [10]int = [99...];
	let arrslice = array[3..5];
	fmt::print("Sub-slice from array: ")!;
	print(arrslice);

	// By omitting the start and end indicies when slicing you can
	// "convert" an array to a slice if needed.
	fmt::print("Convert from array: ")!;
	print(array[..]);
};

fn print(s: []int) void = {
	for (let e .. s) {
		fmt::print(e, " ")!;
	};
	fmt::println()!;
};
$ hare run slices.ha
4/4 tasks completed (100%)
Empty: 
Append single: 99  
Append multiple: 99  11  22  33  
Head: 99  11  
Tail: 22  33  
Mid: 22  
Insert: 99  11  22  88  33  
Delete single: 99  11  22  33  
Delete multiple: 99  11  
Sub-slice from array: 99  99  
Convert from array: 99  99  99  99  99  99  99  99  99  99