Tzopilotl
Docs
GitHub

Tzopilotl by Example

15. Sets

15.1 Set Literals

-- Create a set with Set(elements...)
let s = Set(1, 2, 3, 4, 5);

-- Set type annotation: Set<T>
let names Set<String> = Set("Alice", "Bob");

15.2 Membership and Modification

let s = Set(1, 2, 3);

-- contains
s contains(2) println;          -- true
s contains(5) println;          -- false

-- add returns a NEW set; the input is unchanged
let s2 = s add(4);
s2 println;                      -- Set(1, 2, 3, 4)

-- remove returns a new set without the element
let s3 = s remove(2);
s3 println;                      -- Set(1, 3)

-- insert! mutates the set in place (returns the same set for chaining)
var t = Set(1, 2);
t insert!(3);
t insert!(2);                    -- duplicate; no-op
t length println;                -- 3

-- pop! mutates and returns one arbitrary element
let e = t pop!;
t contains(e) println;           -- false (e was just removed)

-- copy: sets are passed by reference; copy when an alias must be independent
var u = t copy;
t insert!(99);
u contains(99) println;         -- false

15.3 Set Operations

let a = Set(1, 2, 3, 4);
let b = Set(3, 4, 5, 6);

union(a, b) println;             -- Set(1, 2, 3, 4, 5, 6)
intersection(a, b) println;      -- Set(3, 4)
difference(a, b) println;        -- Set(1, 2)

15.4 Conversion and Size

let s = Set(3, 1, 2);

s length println;                -- 3
s toArray println;               -- [3, 1, 2]

Mutability

Sets are heap-allocated and passed by reference. The non-! functions (add, remove, union, intersection, difference) build and return new sets. insert! and pop! mutate the receiving set in place. Use copy when an alias needs to be mutated independently of the original.