Skip to content
Draft

Collections

Draft provides three primary collection types: arrays, maps, and sets.

Ordered, indexed collections of same-type elements.

@numbers: Array<Int> = [1, 2, 3, 4, 5]
@names: Array<String> = ["Alice", "Bob", "Charlie"]
@empty: Array<Float> = []
@list = [1, 2, 3]
@repeated = [0; 10] @// Array of 10 zeros
@first = @list[0] @// 1
@last = @list[@list#length - 1] @// 3
mut @list = [1, 2, 3]
@list[0] = 10 @// [10, 2, 3]
@list#push(4) @// [10, 2, 3, 4]
@list#pop() @// Returns 4, list is [10, 2, 3]
@list#insert(1, 99) @// [10, 99, 2, 3]
@list#remove(1) @// Removes element at index 1
@list#length @// Number of elements
@list#is_empty @// true if length == 0
@list#first @// First element
@list#last @// Last element
@list#slice(1, 3) @// Sub-array from index 1 to 3
@list#reverse() @// Reversed copy
@list#sort() @// Sorted copy
@list#map(fn(@x) => @x * 2) @// Transform each element
@list#filter(fn(@x) => @x > 2) @// Keep matching elements
@list#reduce(0, fn(@acc, @x) => @acc + @x) @// Sum all
@list#contains(3) @// true if element exists
@list#index_of(3) @// Index of first occurrence
for @item in @list
write(@item)
fin for.
for @index, @item in @list
write(string(@index) + ": " + string(@item))
fin for.

Key-value pair collections.

@scores: Map<String, Int> = {"Alice": 95, "Bob": 87}
@empty: Map<String, String> = {}
@score = @scores["Alice"] @// 95
@maybe = @scores#get("Dave") @// Option<Int>
mut @scores = {"Alice": 95}
@scores["Bob"] = 87 @// Insert or update
@scores#insert("Charlie", 92) @// Insert
@scores#remove("Alice") @// Remove key
@scores#length @// Number of entries
@scores#is_empty @// true if empty
@scores#keys @// Array of keys
@scores#values @// Array of values
@scores#contains("Alice") @// true if key exists
for @key, @value in @scores
write(@key + ": " + string(@value))
fin for.

Collections of unique elements.

@unique: Set<Int> = {1, 2, 3, 4, 5}
@letters: Set<Char> = {'a', 'b', 'c'}
@a = {1, 2, 3}
@b = {2, 3, 4}
@a#union(@b) @// {1, 2, 3, 4}
@a#intersection(@b) @// {2, 3}
@a#difference(@b) @// {1}
@symmetric_diff(@a, @b) @// {1, 4}
mut @set = {1, 2, 3}
@set#add(4) @// Add element
@set#remove(2) @// Remove element
@set#contains(3) @// true
for @item in @set
write(@item)
fin for.
Operation Array Map Set
Access O(1) O(1) O(1)
Insert O(1)* O(1) O(1)
Remove O(n) O(1) O(1)
Search O(n) O(1) O(1)

*Amortized for push at end

Use Case Collection
Ordered list of items Array
Fast lookup by key Map
Unique items, membership test Set
Stack (LIFO) Array (push/pop)
Queue (FIFO) Array (push/shift)

Continue to Strings for string manipulation.