sum across an array of objects

Jonathan M Davis jmdavisProg at gmx.com
Sat Jul 28 01:32:45 PDT 2012


On Saturday, July 28, 2012 09:58:32 Philip Daniels wrote:
> I have an array of objects that have a size() property. Code to
> sum them manually works fine, as expected:
> 
>    auto total = 0;
>    foreach (wt; _word_tables)
>      total += wt.size();
>    return total;
> 
> 
> How can I do this with reduce? (BTW I second the old comments and
> bugs about not having sum() built into the library, it's
> annoying.)
> 
> I tried
> 
>    auto total = reduce!(
>      (int a, WordTable b) { return a + b.size(); })
>      (0, _word_tables);
> 
> but it seems that reduce expects a and b to be of type WordTable,
> so it won't instantiate the template. It's also as long as the
> manual version :-(
> 
> I really want to do
> 
>    auto total = sum(a => a.size(), _word_tables)
> 
> if that's possible.

How about

import std.algorithm;
import std.array;
import std.stdio;

void main()
{
    auto stuff = ["hello world",
                  "Goodbye, Shirley",
                  "Babylon 5 rocks"];

    auto result = reduce!"a + b.length"(0L, stuff);
    assert(result == join(stuff).length);
}

The first parameter is the sum, and the second is the item. So, I expect that

auto total = reduce!((a, b) => a + b.size())(0, _word_tables);

would work for you.


- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list