Issue 9841 - std.algorithm.iFilter
Summary: std.algorithm.iFilter
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2013-03-30 14:06 UTC by bearophile_hugs
Modified: 2024-12-01 16:17 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2013-03-30 14:06:44 UTC
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 Seb 2018-02-10 23:27:47 UTC
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 dlangBugzillaToGithub 2024-12-01 16:17:10 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/phobos/issues/9602

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB