Getting a total from a user defined variable
Salih Dincer
salihdb at hotmail.com
Fri Apr 21 22:55:05 UTC 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 at 79
More information about the Digitalmars-d-learn
mailing list