Comment #0 by bearophile_hugs — 2013-03-30T14:06:44Z
This is a little "challenge" on streams, LINQ, etc:
Challenge 2: Indexed Filtering
Find all the names in the array "names" where the length of the name is less than or equal to the index of the element + 1.
With LINQ:
string[] names = { "Sam", "Pamela", "Dave", "Pascal", "Erik" };
var nameList = names.Where((c, index) => c.Length <= index + 1).ToList();
In D:
auto names2 = ["Sam","Pamela", "Dave", "Pascal", "Erik"];
auto nameRange = iota(size_t.max)
.zip(names2)
.filter!q{ a[1].length <= a[0] }
.map!q{ a[1] };
nameRange.writeln;
Using enumerate() I have suggested in Issue 5550 the D code improves:
auto nameRange2 = names2
.enumerate
.filter!q{ a[1].length <= a[0] }
.map!q{ a[1] };
nameRange2.writeln;
But in this case an iFilter is better than using enumerate+filter+map. In iFilter the filtering function is supplied by an index+item 2-tuple, so the D code becomes:
auto nameRange2 = names2.iFilter!q{ a.length <= i };
So I suggest to add a iFilter or ifilter to Phobos. An alternative name is filterWithIndex, but iFilter is better because it reminds us that the index is the fist items of the 2-tuple.
Comment #1 by greensunny12 — 2018-02-10T23:27:47Z
So summarizing the status quo in D is:
---
auto names2 = ["Sam", "Pamela", "Dave", "Pascal", "Erik"];
auto nameRange2 = names2.enumerate.filter!(a => a.value.length <= a.index).map!(a => a.value);
nameRange2.writeln;
---
https://run.dlang.io/is/SzLRES
It's not too bad and I doubt that filterIndex would be accepted.
Comment #2 by robert.schadek — 2024-12-01T16:17:10Z