Key and value with ranges
Joel
joelcnz at gmail.com
Mon Oct 2 22:51:10 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.”;
>
> void main(string[] args) {
> int[string] dic;
> struct WordCnt {
> string word;
> ulong count;
> string toString() const {
> return text("Word: ", word, " - number of
> instances: ", count);
> }
> }
> WordCnt[] wc;
> data
> .map!(c => lowercase.canFind(std.uni.toLower(c)) ? c :
> ' ')
> .to!string
> .splitter
> .each!(d => dic[d]+=1);
> foreach(key, value; dic)
> wc~=WordCnt(key, value);
> wc.sort!"a.count>b.count".each!writeln;
> }
> ```
>
> How can I improve this code? Like avoiding using foreach.
This is what I've got so far. Is there a way to do it any better?
```d
import std;
auto data="I went for a walk, and fell down a hole.";
void main() {
int[string] aa;
struct WordCnt {
string word;
ulong count;
string toString() const {
return text("Word: ", word, " - number of instances:
", count);
}
}
WordCnt[] wc;
data
.map!(c => lowercase.canFind(std.uni.toLower(c)) ? c : '
')
.to!string
.splitter
.each!(d => aa[d]+=1);
aa.each!((key, value) {
wc~=WordCnt(key, value);
});
wc.sort!"a.count>b.count"
.each!writeln;
}
```
More information about the Digitalmars-d-learn
mailing list