digitalmars.D.learn - Getting a total from a user defined variable
- Joel (12/12) Apr 20 2023 ```d
- John Chapman (2/3) Apr 20 2023 p.map!(x => x.age).sum();
- Joel (2/5) Apr 20 2023 Or: p.map!"a.age".sum; works too.
- Salih Dincer (27/28) Apr 21 2023 If it was me I would use each(). But D is such a powerful
- Ferhat =?UTF-8?B?S3VydHVsbXXFnw==?= (12/24) Apr 20 2023 ```d
- Steven Schveighoffer (8/8) Apr 20 2023 ```d
```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
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
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:Or: p.map!"a.age".sum; works too.// how do I get the total of ages added together?p.map!(x => x.age).sum();
Apr 20 2023
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
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
```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