PeaBox Lab › PeaLang › Learn › Chapter 5 › Lesson 2

Part I — Foundations · Chapter 5 · Lesson 2 of 5 · 10 min read

Lesson 2: Indexing, Slicing, Mutation, Copying, and Equality

Lesson level: Foundation

Purpose: Access and update collection data safely while reasoning about boundaries, shared references, copies, and value comparison.

Learning objectives

By the end of this lesson, you should be able to:

1. Indexing selects one element

Lists, strings, and other indexed values use zero-based positions. The first element is at index 0, the second at index 1, and the last valid nonnegative index is one less than the collection length.

let priorities = ["low", "medium", "high"] print(priorities[0]) print(priorities[2])

The outputs are low and high. An index identifies a position, not an item count.

2. String indexing

A string can be indexed to select a character position:

let code = "PEA" print(code[0]) print(code[2])

The selected results are P and A. Treat indexing as reading a position; string construction and transformation should use clear string operations rather than assuming arbitrary in-place character mutation.

3. Valid index boundaries

For a collection of length n, valid nonnegative indices run from 0 through n - 1. Accessing an invalid index produces an error.

let values = [10, 20, 30] let index = 2 if index >= 0 and index < 3 { print(values[index]) }

In reusable code, derive bounds from the collection through supported operations rather than duplicating a literal length that can drift.

4. Map key access

Maps are accessed by string key rather than numeric position:

let case = {"id": "CASE-1042", "impact": 6} print(case["id"])

A key describes field meaning. Key spelling and case are part of the contract.

5. Check key presence first

Do not access an untrusted map key before confirming its presence through supported map operations. A missing key differs from a present key whose value is null.

Validation order is: confirm the map shape, confirm the required key, read the value, check nullability, then validate the value's category and domain constraints.

6. Slicing selects a subsequence

A slice selects a range from an indexed value. The start is included and the stop is excluded, matching the range boundary model used in loops.

let values = [10, 20, 30, 40, 50] let middle = values[1:4]

The result contains 20, 30, and 40. The stop index 4 marks the first element not included.

7. Slice boundaries

Reason about a slice with three questions:

For values[1:4], the included indices are 1, 2, and 3, producing three elements.

8. String slices

Slicing a string selects a substring:

let identifier = "CASE-1042" let prefix = identifier[0:4]

The result is CASE. Use slices when positions are defined by the contract; otherwise prefer named parsing or string operations that reveal intent.

9. Empty slices

A valid slice can produce an empty result when its selected interval contains no elements. This differs from an invalid single-element index, which cannot return an element.

Test empty collections, equal start and stop positions, beginning boundaries, ending boundaries, and the full selected range.

10. Slices and copies

A slice produces a separate outer collection value rather than an alias to the original list container. Mutating the outer slice should not change the original list structure. However, nested mutable values can still be shared, so the copy is shallow unless the contract states otherwise.

11. Mutation changes an existing collection

Mutation changes part of a list or map while the binding continues to refer to the same collection value.

let scores = [8, 9, 10] scores[1] = 12 let case = {"status": "new"} case["status"] = "assigned"

The list's second element changes, and the map's status field changes.

12. Rebinding versus mutation

Rebinding assigns a different value to a name. Mutation updates the collection already referenced by that name.

let values = [1, 2, 3] values[0] = 9 values = [4, 5, 6]

The first update mutates the original list. The second rebinds values to another list.

13. const protects the binding

A const declaration prevents rebinding. When the bound value is mutable, const does not automatically imply a deeply immutable object. Keep the distinction explicit and avoid mutating collections that readers reasonably expect to remain fixed.

For policy data, prefer functions that return new collections when mutation would obscure ownership or create shared-state risk.

14. Validate writable targets

Before assigning through an index or key, confirm that the target supports mutation and that the position or key operation is valid. An arbitrary calculated expression is not a writable location.

Keep mutation local, purposeful, and close to its validation. Document which function owns the collection and which callers may retain references to it.

15. Mutation and invariants

Every update should preserve collection invariants. Examples include:

Validate the proposed value before writing it, then verify any relationship that spans several fields.

16. Assignment can create aliases

When one binding receives an existing list or map, both names may refer to the same mutable collection.

let original = [1, 2, 3] let alias = original alias[0] = 9

If the bindings share the same list, reading original[0] now returns 9. The assignment copied the reference, not an independent outer collection.

17. Why aliasing matters

Aliasing makes an update visible through every reference to the same collection. This can be intentional, but hidden aliases make local-looking changes affect distant code.

Before mutating a collection, ask who else can reference it. Establish ownership rules: mutate only owned collections, or return a new value when callers may share the original.

18. Shallow copies

A shallow copy creates a new outer list or map while reusing nested values. A full list slice is one way to produce a separate outer list where supported:

let original = [1, 2, 3] let copied = original[0:3] copied[0] = 9

The outer list structure is separate, so the original first element remains 1.

19. Nested aliasing after a shallow copy

Consider a list of maps:

let original = [{"quantity": 2}, {"quantity": 5}] let copied = original[0:2] copied[0]["quantity"] = 9

The outer lists are separate, but the nested first map may still be shared. A shallow copy does not recursively duplicate nested collections.

20. Deliberate deep copying

When nested independence is required, construct new nested lists and maps deliberately or use a documented library operation that guarantees the needed copy depth. State whether an interface returns shared data, a shallow copy, or a fully independent portable structure.

Deep copying every value automatically can be expensive and may hide an unclear ownership design. Copy only to satisfy a defined contract.

21. Copy-before-update pattern

This pattern is useful when a function should behave like a transformation rather than an in-place editor.

22. Scalar equality

The equality operators compare values. Strings compare text exactly, booleans compare their true or false value, null equals null, and numbers compare numerically under the language's value rules.

print("gold" == "gold") print(true != false) print(null == null)

Do not confuse equality with assignment. Equality produces a boolean; assignment changes a target.

23. Collection equality

Lists and maps compare by their contained values rather than merely by whether two bindings refer to the same container. List order matters. Maps must have corresponding keys and equal values.

Nested collections compare recursively. A small difference deep inside a structure makes the whole comparison unequal.

24. Equality versus aliasing

Two collections can be equal without being the same shared collection, and two aliases can refer to the same collection. Equality alone does not reveal whether later mutation will be shared.

Test independence by applying a controlled mutation to a copy in a dedicated test and confirming whether the source changes. Do not use destructive probes in production logic.

25. Floating-point comparison

Exact equality may be unsuitable for values produced by floating-point arithmetic. Use an explicit tolerance:

let difference = calculated - expected if difference < 0 { difference = -difference } let close_enough = difference <= tolerance

The tolerance belongs in the domain contract. Do not choose it merely to make a failing test pass.

26. Equality and domain equivalence

Value equality and business equivalence are not always identical. Case-normalized labels, reordered records, or rounded measurements may be equivalent only after an explicit normalization policy.

Keep normalization separate and visible. Compare canonical values after validation rather than silently converting unrelated inputs during equality checks.

27. Common mistakes

Guided practice

Hands-on lab: Build a safe inventory updater

Scenario. An inventory is represented as a list of string-keyed item maps. Build functions that read, update, copy, and compare the inventory without accidental shared mutation.

Item contract

Requirements

Test cases

Deliverable. Submit the source, ownership notes, alias diagram, test matrix, before-and-after states, equality results, and invariant evidence.

Review questions

Applied challenge: Non-destructive order revision

Build a function that receives a portable order map containing a list of line-item maps and returns a revised order without mutating the source. It must validate the target item index, rebuild the required nested structures, update quantity, and recalculate summary fields.

Prove that the source and revised order are equal before the change except for intentionally updated fields, and prove that later nested mutation of the revised order does not alter the source. Include invalid-index, missing-key, null-field, negative-quantity, empty-order, and floating-point tolerance tests.

Success criteria

Lesson summary

Indexing reads one position, while slicing selects a subsequence with an exclusive stop boundary. Collection updates require valid writable targets and preserved invariants. Rebinding changes which value a name references; mutation changes an existing collection. Assignment can create aliases, shallow copies separate only the outer collection, and nested values may remain shared. Equality compares values but does not prove reference independence, while derived floating-point values often require tolerance-based comparison.

Next lesson: Traversal, Transformation, Filtering, and Aggregation

Lesson status: Approved.

← Previous Next →