Key and value with ranges

christian.koestlin christian.koestlin at gmail.com
Mon Oct 2 18:46:14 UTC 2023


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


More information about the Digitalmars-d-learn mailing list