sum across an array of objects
Philip Daniels
Philip.Daniels1971 at gmail.com
Sat Jul 28 10:06:21 PDT 2012
On Saturday, 28 July 2012 at 14:36:26 UTC, Ali Çehreli wrote:
> On 07/28/2012 06:49 AM, Philip Daniels wrote:
>
> > It seems to
> > be something to do with whether the array is static or
> dynamic.
>
> Good catch! :) Welcome to D where static arrays (aka
> "fixed-length arrays") and dynamic arrays (aka "slices") are
> different beasts.
>
> A number of factors are at play here:
>
> 1) Static arrays are value types. As a result, the entire array
> gets copied when pass to a function (e.g. reduce) as an
> argument.
>
> 2) The length of static arrays cannot change.
>
> 3) Phobos is a range-based library. reduce() is an algorithm
> that not more than an InputRange.[*] InputRanges are naturally
> consumed as they are being iterated over.
>
> For the reasons above, a static array is not usable by
> reduce(). Your solution of taking a slice of all of the
> elements first by _word_tables[] is the correct solution (and
> very cheap, thanks to D's slices).
>
> Ali
>
> [*] Arguably, reduce() could have a specialization that worked
> on RandomAccessRanges (static arrays included), making life
> easier. I don't see why that could not be added to Phobos.
Thanks for the explanation Ali. I was planning on converting the
array to dynamic anyway, since the ultimate size is dependent
upon the program's input, so I think I'll do that now.
More information about the Digitalmars-d-learn
mailing list