🐺 WOLFRAM ALCHEMY DIFFICULTY: Apprentice Behavioral

The Iterator Incantation

Traversing a collection of artifacts without exposing their underlying representation.

✧ GANG OF FOUR LINEAGE & ARCANUM ✧
GOF DESIGN PATTERN: Iterator
ARCANUM SCHOOL: Divination // Sequencing
SCRIBE / ARCHON: Joshua Edward McLaughlin Cox
CANONICAL REGISTRATION:
// MATHEMATICA PATTERN //
(* In Mathematica, Map, Scan, and Table act as native iterators. *)
(* However, we can construct a stateful iterator closure for pure magic. *)
ClearAll[CreateGrimoireIterator];

CreateGrimoireIterator[spells_List] := Module[{index = 1, len = Length[spells]},
  <|
    "HasNext" :> (index <= len),
    "Next" :> (If[index <= len, 
                 With[{val = spells[[index]]}, index++; val], 
                 Null]),
    "Reset" :> (index = 1)
  |>
];

(* Usage *)
grimoire = {"Levitate", "Fireball", "Invisibility"};
iterator = CreateGrimoireIterator[grimoire];

While[iterator["HasNext"],
  Print["Reading spell: ", iterator["Next"]]
];
Runic Tags: #iterator #behavioral #closures #traversal