foreach, an analogy
Gregor Richards
Richards at codu.org
Wed Oct 18 20:35:55 PDT 2006
Bill Baxter wrote:
> I like analogies, so here goes one. If you don't just skip it. :-)
>
> Say you've built a house and you're almost done, but you find one
> doorway with a door that's about an inch too narrow for the frame. You'd
> really like to cover that gap somehow. You could just leave it as-is.
> Sure. You've got *most* of the doorway covered after all. It's not
> like a criminal could sneak in through a one-inch gap. Still, it could
> get pretty cold in the winter, so you'd really like to fix it.
>
> Clearly the best solution long term is to get a bigger door.
>
> But you don't have a bigger door. You do, however, have a clever
> solution: take another door, identical to the first, and hang it on the
> *other side* of the frame to cover the gap. Perfect! The gap is covered!
>
> But hmm. Now there are two doors. Either of them alone *almost* enough
> to cover the doorway. You don't really _need_ two doors doing almost
> exactly the same thing.
>
> It's not so bad, though. At least in the summer, when you don't need
> it, you can just leave that second door open and out of the way. Even
> take it off its hinges and put it in the basement.
>
> That second door, as I'm sure you've figured out, is foreach_reverse.
>
> And really I do believe it's not so bad. It's an ugly hack, like
> hanging a second door to fill a small gap, but if you don't want to
> iterate backwards over arrays as fast as possible, then you're free to
> ignore it, put that door in the basement, and use whatever technique you
> prefer.
>
> However, I still hope the plan is to one day get a bigger door.
>
> --bb
The bigger door is 'for'. 'foreach' is nothing but a convenient wrapper
around 'for'. And don't you OOphiles go telling me that your fancy
class foo that has iteration /needs/ 'foreach':
for (auto bar = foo.begin(); !(bar is null); bar = foo.iterate(bar))
Is it less pretty than foreach? Yeah. That's why foreach exists. But
don't go saying that the reverse foreach is a band-aid patch, because
both forms are just convenience wrappers around the far more powerful
and useful 'for'. Your small door is actually the screen door.
- Gregor Richards
More information about the Digitalmars-d-announce
mailing list