you can specify the functions front
, popfront()
and empty
: (but this will consume your collection if you do not use save ())
public class Collection(T) { ... private T head; private Collection!(T) queue; @property T front(){ return head; } @property bool empty(){ return queue is null; } void popfront(){ head = queue.head; queue = queue.queue; } Collection!T save(){ return new Collection!T(head,queue); } }
or use the selected structure for iteration (as is done in the std.container
module
public class Collection(T) { ... private T head; private Collection!(T) queue; Range opSlice(){ return Range(head,queue); } struct Range{ T h; Collection!(T) q; this(T he, Collection!(T) qu){ h=he; q=qu; } @property T front(){ return h; } @property bool empty(){ return q is null; } void popfront(){ h = q.head; q= q.queue; } Collection!T save(){ return this; } } }
therefore iteration is performed like this:
Collection!(int) temp; foreach (int t;temp[]) { ... }
you can also add opApply
for regular foreach:
public int opApply(int delegate(ref T) dg){ int res=0; foreach(ref T;this[]){ res = dg(t); if(res)return res; } return res; }
source share