foreach, an analogy
Pragma
ericanderton at yahoo.removeme.com
Thu Oct 19 13:17:57 PDT 2006
Jarrett Billingsley wrote:
> You can have:
>
> something.each((int item) {
> writefln(item);
> });
I like the look of that. I've been doing a lot of Javascript coding
with Prototype lately, and I really gotten used to using closures in
this way.
But it's almost a parallel solution to for/foreach anyway. If IFTI were
a little smarter, you wouldn't need compiler support to pull it off. As
a bonus, that would mean that all the other kinds of iteration
imaginable (unordered, reverse, sorted, etc) would just be additional
iterator templates.
// fn returns false to break the loop, true to continue
void each(T)(T[] arr, int delegate(inout T) fn){
for(uint i=0; i<arr.length; i++) if(!fn(arr[i])) break;
}
void reverse(T)(T[] arr, int delegate(inout T) fn){
for(uint i=length-1; i>=0; i--) if!(fn(arr[i])) break;
}
AFAIK, I'm mostly sure this will work now. Haven't tried it though.
Aside from not being able to use break and continue to control the loop
behavior, I'd happily use a library that does this. Prototype uses
"throw BREAK;" (where 'BREAK' is a constant defined elsewhere) which
might be a better looking solution, if a bit kludgey.
- EricAnderton at yahoo
More information about the Digitalmars-d-announce
mailing list