Implementing non-stateful iteration


#1

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/


#2

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


#3

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


#4

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


#5

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

#6

Ah that’s good. Thanks!