Iterator

Context: FIT1008_MOC · the stateful “bookmark” that walks an Iterable · realised by LinkListIterator · built on Node traversal

Quick Revision

  • 🎯 Objective: a bookmark object remembering where you are âž” yields the next element on request.
  • 📦 Core Components: __next__ (next or StopIteration) + __iter__ (returns self) âž” external (pull) vs internal (push).
  • ⚡ Key Constraint: per next, space (stores only the cursor); single-use and invalid if the collection mutates (fail-fast).

📝 Core

1. The Iterator (Cursor Object)

  • Separate object âž” remembers the position, yields the next element âž” advancing changes its own state, not the data.
  • Coexistence âž” several iterators can walk one Iterable at once.
  • Protocol âž” __next__ + __iter__ (returns self); driven by next(it).
  • Single-use âž” once exhausted stays exhausted; space âźą mutating the collection invalidates it.

2. External vs Internal Iteration

  • External (pull) âž” client calls next and controls the loop âž” early stop, zip two iterators, pause/resume.
  • Internal (push) âž” collection pushes each element to a callback (Tree Traversal’s f, map, forEach).
  • Fail-fast âž” detects structural modification during iteration and raises (Java ConcurrentModificationException, Python RuntimeError).

⚙️ Core Implementation

🔹 LinkListIterator

When It Flips: external (pull) is flexible — for x in it, early break, interleave with zip; internal (push) encapsulates order — map(f, xs), tree callback. For deliberate mutation during traversal use a modifying iterator (LinkListIterator), not a fail-fast read-only one.

📊 Exam Execution Trace

Manual Execution Trace

Driving an iterator over 1 -> 2 -> 3:

Step / StateCallcurrentReturns
0 (Init)—node 1—
1nextnode 1 → node 21
2nextnode 2 → node 32
3nextnode 3 → None3
4nextNoneStopIteration

Applied Exercise

Problem: Contrast who owns the loop in external vs internal iteration. Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: external wins on control; internal on encapsulating traversal order.

đź§  Active Recall