Implementing non-stateful iteration


I’m trying to wrap a C library where iteration is intrinsically non-stateful, as shown below.

void *y = ...;
void *x = start_iteration(y);
while (x!=NULL) {
  x = get_next(y);

I was wondering if anyone has any advice on how to (elegantly) wrap this iteration pattern with the Julia iteration protocol, where there doesn’t seem to be a natural definition of state as in


This iteration looks super stateful… In fact, x itself is the state.


Oh woops, typo. It should be x = get_next(y); the C library has some internal opaque state attached y.


Then just use nothing as state, that’s what we do with files.


A common pattern I’ve used is to stash the subsequent object as your state. In pseudo-code:

start(y) = next(y, start_iteration(y))[2]
next(y, state) = (do_something(state); (state, get_next(y)))
done(y, state) = state == NULL


Ah that’s good. Thanks!