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) {
  do_something(x);
  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 http://docs.julialang.org/en/release-0.5/manual/interfaces/

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
1 Like

Ah that’s good. Thanks!