The lifetime of reduce's internal seed

monarch_dodra via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 22 11:45:42 PDT 2014


On Tuesday, 22 April 2014 at 18:17:58 UTC, Ali Çehreli wrote:
> On 04/22/2014 11:03 AM, monarch_dodra wrote:
> > The "int[] reduce...", however, I think is a outright
> language issue.
> > Implicilty calling opSlice on a static array is one thing,
> but doing it
> > on an rvalue is an outright aberration. The code should be
> rejected no
> > questions asked.
>
> I don't think there is slicing an rvalue though. (?) reduce() 
> is taking a copy of the seed and then returning a slice to it 
> because the user slices it in their lambda. It effectively does 
> the following, which unfortunately compiles:
>
> int[] foo()
> {
>     int[1] sum;
>     return sum[];    // <-- no warning
> }

Reduce returns "the seed". It's actually doing something more 
like this:

int[1] foo()
{
     int[1] sum
     sum = sum[]; //The lambda operates, and the
                  //result is assigned back to the seed.
     return sum; //Returns the seed.
}

So when writing:

> void main()
> {
>     int[] result = foo();
> }

There's a *second* level of bug. (assigning an rvalue "int[1]" to 
int[])

*This* works fine though:
     int[1] seed;
     int[1] result = reduce!((ref sum, _) => sum)(seed, arr);

BTW, I'm re-implemented reduce recently (not yet pulled), but I 
was *very* thorough about documenting what it does:
https://github.com/D-Programming-Language/phobos/pull/2060

Could you take a look at it (the documentation I mean), and tell 
me if everything is what you would have expected?


More information about the Digitalmars-d-learn mailing list