dsimcha wrote:
== Quote from Andrei Alexandrescu ([email protected])'s article
dsimcha wrote:
== Quote from Max Samukha ([email protected])'s article
On Tue, 20 Jan 2009 12:23:58 +0300, "Denis Koroskin"
<[email protected]> wrote:
One nice thing that opApply capable of is it can avoid heap activity by
stack-allocating data during iteration.
For example, given an array of ints, iterate over string representations of
them:
struct IntegersAsString
{
void opAplly(int delegate(string s) dg)
{
char[16] temp;
foreach (i; array) {
int len = sprintf(temp, "%d", i);
int result = dg(temp[0..len]);
if (result != 0) {
return result;
}
}
return 0;
}
private int[] array;
}
int array = [1, 1, 2, 3, 5, 8, 13];
// no heap allocation take place
foreach (string s; IntegersAsString(array)) {
writeln(s);
}
How would you do that with ranges?
struct IntegersAsString
{
private
{
int[] array;
char[16] temp;
}
char[] head()
{
int len = sprintf(temp.ptr, "%d", array[0]);
return temp[0..len];
}
void next()
{
array = array[1..$];
}
bool empty()
{
return array.length == 0;
}
}
void main()
{
int[] array = [1, 1, 2, 3, 5, 8, 13];
// no heap allocation take place
foreach (char[] s; IntegersAsString(array))
writefln(s);
}
Yet another argument for some kind of opRange to syntactically sugar this up.
Where would that be useful in this example?
Andrei
foreach(char[] s; array) vs.
foreach(char[] s; IntegersAsString(array))
Oh, that's not opRange helping, it's head() with parameterized return type.
I think a lot of stuff is going to need some kind of extra struct like this to
make it work. When this is the case, it needs to be possible to have a default
iteration method that "just works." The opDot overload, I guess, could do this,
but it's a rather blunt tool, since then you can't use opDot for other stuff and
you'd have to forward _everything_ to the opDot object.
How does opDot intervene here?
Andrei