how does range.put work

Jos van Uden jvu at nospam.nl
Sat Aug 8 05:50:27 PDT 2009


Daniel Keep wrote:

> No; read the code.  Before the put, a and b are pointing to the same
> span of memory.  a.put(5) puts the value 5 into the front (first
> element) of the array, then advances the array.
> 
> However, put can't "see" b, so it doesn't get updated along with a.  The
> end result is that b = [5,2,3] and a = b[1..3] = [2,3].
> 
> Why do it like this?  Here's an example:
> 
> void putNumbers(Range)(Range r)
> {
>     int i = 0;
>     while( !r.empty )
>     {
>         r.put(i);
>         ++i;
>     }
> }
> 
> void main()
> {
>     int[10] ten_numbers;
>     putNumbers(ten_numbers);
>     assert( ten_numbers = [0,1,2,3,4,5,6,7,8,9] );
> }

I see.

Your example should be in the documentation in my opinion, rather
then the meaningless one that's there now. Something like this
perhaps:

void putNumbers(Range, T)(Range r, T start, T incr) {
     T i = start;
     while( !r.empty )
     {
         r.put(i);
         i += incr;
     }
}

void main() {
    int[10] ten_ints;
    putNumbers!(int[])(ten_ints, 4, 2);
    assert( ten_ints == [4,6,8,10,12,14,16,18,20,22] );
}

Jos




More information about the Digitalmars-d-learn mailing list