www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Getting a total from a user defined variable

reply Joel <joelcnz gmail.com> writes:
```d
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?
}
```
Apr 20 2023
next sibling parent reply John Chapman <johnch_atms hotmail.com> writes:
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();
Apr 20 2023
parent reply Joel <joelcnz gmail.com> writes:
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.
Apr 20 2023
parent Salih Dincer <salihdb hotmail.com> writes:
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: ```d 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
Apr 21 2023
prev sibling next sibling parent Ferhat =?UTF-8?B?S3VydHVsbXXFnw==?= <aferust gmail.com> writes:
On Thursday, 20 April 2023 at 19:41:21 UTC, Joel wrote:
 ```d
 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?
 }
 ```
```d 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"); } ```
Apr 20 2023
prev sibling parent Steven Schveighoffer <schveiguy gmail.com> writes:
```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
Apr 20 2023