3 ms·
The post about internal and external iteration is fantastic and definitely makes a good argument for a language supporting both (which newer versions of Ruby do
by sanderjd 13y ago
The post about internal and external iteration is fantastic and definitely makes a good argument for a language supporting both (which newer versions of Ruby do, actually), but this part left me scratching my head:
> As far as I can tell, you simply can’t solve [the interleave example problem] using internal iterators unless you’re willing to reach for some heavy weaponry like threads or continuations.
I must be missing something, because it doesn't seem particularly hard:
class Array
def interleave_each(other)
self.zip(other).each do | a, b |
yield a if a
yield b if b
end
end
end
Am I cheating somehow, or have I misunderstood the problem?
Edit: Ah, I see, the problem is that I'm relying on the specific semantics of lists, which works for the example as written, but not for the general case (ie. if I have one file and one list).
- TheCoelacanth 13y agoYou "cheated" by using zip. You can't easily implement zip using only internal iterators but you easily can using external iterators. If you look at a slightly different problem that doesn't precisely fit the special case of zip you'll see the difficulty involved with using internal iterators.
- nimish 13y agoWhere does haskell fit on this paradigm? You can derive "internal" iterators using Traversable but it's not like zip is difficult to implement.
- pcwalton 13y agoHaskell typically uses internal iterators, but because it's lazy many composition strategies are more straightforward. Rust is strict, however, so the same techniques don't apply.
- koomi 13y agoThere is no general zip for every Traversable, though there is one for every Applicative with a suitable instance (like the ZipList wrapper for lists): liftA2 (,) The reason is that you need to operate on multiple containers at once and that is what Applicative's (<*>) provides, while Traversable only requires Functor and can therefore only traverse one container at a time. So what Haskell has is just internal iteration, but we have another interface for internal iteration on multiple containers that allows zip to be implemented easily.