Thread overview
Getting a total from a user defined variable
Apr 20
Joel
Apr 21
Joel
April 20
import std;

struct Person {
    string name;
    ulong age;
}

void main() {
    auto p=[Person("Joel", 43), Person("Timothy", 40)];
    writeln("Total: ", p.reduce!((a,b) => a.age+b.age)(0UL)); // how do I get the total of ages added together?
}
April 20

On Thursday, 20 April 2023 at 19:41:21 UTC, Joel wrote:

>

// how do I get the total of ages added together?

p.map!(x => x.age).sum();

April 20

On Thursday, 20 April 2023 at 19:41:21 UTC, Joel wrote:

>
import std;

struct Person {
    string name;
    ulong age;
}

void main() {
    auto p=[Person("Joel", 43), Person("Timothy", 40)];
    writeln("Total: ", p.reduce!((a,b) => a.age+b.age)(0UL)); // how do I get the total of ages added together?
}
import std;

struct Person {
    string name;
    ulong age;
}

void main() {
    auto p=[Person("Joel", 43), Person("Timothy", 40)];

    writeln("Total: ", p.map!(a => a.age).reduce!"a + b");
}
April 20
```d
writeln("Total: ", p.fold!((a,b) => a+b.age)(0UL));
// or
writeln("Total: ", reduce!((a,b) => a+b.age)(0UL, p));
```

Note that `reduce` is the old version of `fold`, which happened when UFCS became a thing.

-Steve
April 21

On Thursday, 20 April 2023 at 21:28:48 UTC, John Chapman wrote:

>

On Thursday, 20 April 2023 at 19:41:21 UTC, Joel wrote:

>

// how do I get the total of ages added together?

p.map!(x => x.age).sum();

Or: p.map!"a.age".sum; works too.

April 21

On Friday, 21 April 2023 at 05:23:14 UTC, Joel wrote:

>

Or: p.map!"a.age".sum; works too.

If it was me I would use each(). But D is such a powerful language that you have many alternatives:

import std.algorithm, std.range, std.stdio;

struct Person { string name; int age; }
auto totalPersonAge = (int result, Person person)
                        => result + person.age;
void main()
{
    auto p = [
         Person("Kocaeli", 41),
         Person("Konya", 42)
    ];

    p.map!(a => a.age).reduce!"a + b".writeln;
    p.map!"a.age".reduce!"a + b".writeln;

    auto result = reduce!((a, b) => a + b.age)(0, p);
    result.writeln;

    assert(result == reduce!totalPersonAge(0, p));
    assert(result == p.fold!totalPersonAge(0));
    assert(p.map!(a => a.age).sum == p.map!"a.age".sum);


    size_t total;
    p.each!( (ref person) => total += person.age);
    total.writeln;
}

SDB@79