sum across an array of objects

Ali Çehreli acehreli at yahoo.com
Sat Jul 28 07:36:25 PDT 2012


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.



More information about the Digitalmars-d-learn mailing list