Another foreach idea.
Kirk McDonald
kirklin.mcdonald at gmail.com
Wed Jun 7 22:56:50 PDT 2006
Kirk McDonald wrote:
> In short, all you need is a "range" function that returns an array of
> integers, or (alternately) a generator... something like this:
>
Oh! I did some thinking and improved it a little. It's a struct now, so
it doesn't need to touch the GC. And factory functions are maybe a
little more clear than static opCalls (also, there are two, now).
private import std.stdio;
struct range_struct {
public:
int m_start, m_end, m_step;
// Compares whether i has reached the end
private bool cmp(int i) {
if (m_step > 0 && i < m_end) return true;
else if (m_step < 0 && i > m_end) return true;
else return false;
}
int opApply(int delegate(inout int) dg) {
int result = 0;
for (int i=m_start; this.cmp(i); i+=m_step) {
result = dg(i);
if (result) break;
}
return result;
}
}
range_struct range(int start, int end, int step=1) {
range_struct r;
r.m_start = start;
r.m_end = end;
r.m_step = step;
return r;
}
range_struct range(int end) {
return range(0, end, 1);
}
void main() {
foreach(i; range(10)) {
writefln("%s", i);
}
foreach(j; range(10, 20)) {
writefln("%s", j);
}
foreach(k; range(0, 10, 2)) {
writefln("%s", k);
}
}
-Kirk McDonald
More information about the Digitalmars-d
mailing list