Re: Getting a total from a user defined variable

2023-04-21 Thread Salih Dincer via Digitalmars-d-learn

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


Re: Getting a total from a user defined variable

2023-04-20 Thread Joel via Digitalmars-d-learn

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.


Re: Getting a total from a user defined variable

2023-04-20 Thread Steven Schveighoffer via Digitalmars-d-learn

```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


Re: Getting a total from a user defined variable

2023-04-20 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

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");
}
```


Re: Getting a total from a user defined variable

2023-04-20 Thread John Chapman via Digitalmars-d-learn

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();


Getting a total from a user defined variable

2023-04-20 Thread Joel via Digitalmars-d-learn

```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?

}
```