Key and value with ranges

Andrey Zherikov andrey.zherikov at gmail.com
Tue Oct 3 01:55:43 UTC 2023


On Monday, 2 October 2023 at 18:46:14 UTC, christian.koestlin 
wrote:
> On Monday, 2 October 2023 at 02:47:37 UTC, Joel wrote:
>> How can I improve this code? Like avoiding using foreach.
>
> You could fold into a hash that counts the occurrences like 
> that:
>
> ```d
> import std.uni : toLower;
> import std.array : split, array;
> import std.stdio : writeln;
> import std.algorithm : fold, sort, map;
>
>
> auto data="I went for a walk, and fell down a hole. a went";
>
> int main(string[] args)
> {
>     int[string] wc;
>     data
>         .toLower
>         .split
>         .fold!((result, element) { result[element] += 1; return 
> result; })(wc)
>         .byKeyValue
>         .array
>         .sort!((pair1, pair2) => pair1.value > pair2.value)
>         .map!(pair => pair.key)
>         .writeln
>         ;
>     return 0;
> }
> ```
>
> Not sure how to get rid of the declaration of the empty wc hash 
> though.
>
> Kind regards,
> Christian

Slightly improved:
```d
import std;

auto data="I went for a walk, and fell down a hole. a went";

int main(string[] args)
{
     data
         .toLower
         .split
         .fold!((ref result, element) { ++result[element]; return 
result; })(uint[string].init)
         .byKeyValue
         .array
         .sort!((pair1, pair2) => pair1.value > pair2.value)
         .each!(pair => writeln("Word: ", pair.key, " - number of 
instances: ", pair.value))
         ;
     return 0;
}
```

Output:
```
Word: a - number of instances: 3
Word: went - number of instances: 2
Word: and - number of instances: 1
Word: i - number of instances: 1
Word: hole. - number of instances: 1
Word: for - number of instances: 1
Word: down - number of instances: 1
Word: fell - number of instances: 1
Word: walk, - number of instances: 1
```


More information about the Digitalmars-d-learn mailing list