HACKER Q&A
📣 brundolf

Iterators in a Pure-Functional Context?


I'm designing a small statically-typed language that has a pure-functional subset. I wanted to have first-class iterator support, which intuitively feels like it dovetails nicely with functions/transformations, but it's occurred to me that iterators are not immutable; they get consumed, which means they can only be used once, which seems like it might still work as long as you can't make intermediate declarations and pass them to multiple other places... right?

I'm a bit new to this stuff, so I'm wondering: how do other pure-functional languages handle iterators? Are they some weird exception? Are they not allowed in pure contexts at all (done using IO monads or something, perhaps)? Do you need full-on move semantics to work with them properly? Is there a strategy for automatically "cloning" an iterator? What are the different approaches here?

I'd prefer to keep my language as simple as possible, so I'd rather avoid going down too deep of a rabbit-hole, even if it means bending the definition of "pure" a little bit.


  👤 mrloba Accepted Answer ✓
I would also like to know, as I started on something similar myself. My plan was to allow calling an impure function from a pure function as long as the mutation was contained to state that had its entire lifetime within the pure function. To ensure that the impure function only did mutations in such a way I planned to add a special keyword that could be type checked. Never got very far with it though.