Can we get rid of opApply?

dsimcha dsimcha at yahoo.com
Tue Jan 20 05:23:41 PST 2009


== Quote from Max Samukha (samukha at voliacable.com.removethis)'s article
> On Tue, 20 Jan 2009 12:23:58 +0300, "Denis Koroskin"
> <2korden at gmail.com> 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.



More information about the Digitalmars-d mailing list