On 16/12/2025 09:07, Tim Düsterhus wrote:
That definition doesn't make sense to me. An iterator that only ever emits a single value is not actually iterating anything and it would never occur me to interpret it like that.


Well, firstly, it is certainly possible to have an iterator that only emits one item; or even no items at all. There are even design patterns that rely on that - in some languages, the Option/Maybe type is a zero-or-one-item iterator, and you unwrap the value using "map" to either call or not call a function.

But that wasn't really the image I was trying to conjure; it's more about the relationship between the Iterator and the item. Here's a metaphor which might or might not work:


You are at an arcade. There is a machine with a single button, and a tray. Every time you press the button, a toy drops into the tray. After you press the button a few times, toys stopping coming out, because there are none left in the machine.

This machine is labelled "Iterator".


Next to it, there is another machine which looks similar. When you press the button on this one, some music starts, and then a toy drops into the tray. When you press the button again, the music stops. No more toys drop.

The toys are not making the music, and the music is not making the toys; they just both happen when you press the button.

This machine is labelled "Context Manager".


Then there's a third machine, which doesn't have the tray, only the button. You press the button once, and the music starts; you press it again, and it stops.

This machine is also labelled "Context Manager".


That's what I mean by "like an iterator with one item": that Iterators and Context Managers are similar kind of machines. The "foreach" and "using" statements don't create or move those machines, they *operate* them, pressing the button so the music plays and the next toy comes out.


--
Rowan Tommins
[IMSoP]

Reply via email to