Key and value with ranges

Joel joelcnz at gmail.com
Tue Oct 3 02:49:52 UTC 2023


On Monday, 2 October 2023 at 02:47:37 UTC, Joel wrote:
> ```d
> import std;
>
> auto data=“I went for a walk, and fell down a hole.”;
> ```

[snip]

>
> How can I improve this code? Like avoiding using foreach.

This works for me:

```d
import std;

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

void main(string[] args)
{
     if (args.length>1 && args[1].exists)
         data=readText(args[1]);
     data
         .toLower
         .map!(c => lowercase.canFind(std.uni.toLower(c)) ? c : ' 
')
         .to!string
         .split
         .fold!((ref result, element) { result[element]+=1; return 
result; })(uint[string].init)
         .byKeyValue
         .array
         .sort!"a.value>b.value"
         .each!(pair => writeln("Word: ", pair.key, " - number of 
instances: ", pair.value));
}
```


More information about the Digitalmars-d-learn mailing list