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?
}
Thread overview | ||||||||
---|---|---|---|---|---|---|---|---|
|
April 20 Getting a total from a user defined variable | ||||
---|---|---|---|---|
| ||||
April 20 Re: Getting a total from a user defined variable | ||||
---|---|---|---|---|
| ||||
Posted in reply to Joel | 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 Re: Getting a total from a user defined variable | ||||
---|---|---|---|---|
| ||||
Posted in reply to Joel | On Thursday, 20 April 2023 at 19:41:21 UTC, Joel wrote: >
|
April 20 Re: Getting a total from a user defined variable | ||||
---|---|---|---|---|
| ||||
Posted in reply to Joel | ```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 Re: Getting a total from a user defined variable | ||||
---|---|---|---|---|
| ||||
Posted in reply to John Chapman | 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 Re: Getting a total from a user defined variable | ||||
---|---|---|---|---|
| ||||
Posted in reply to Joel | 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:
SDB@79 |
Copyright © 1999-2021 by the D Language Foundation