Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std.algorithm.iFilter #9602

Open
dlangBugzillaToGithub opened this issue Mar 30, 2013 · 1 comment
Open

std.algorithm.iFilter #9602

dlangBugzillaToGithub opened this issue Mar 30, 2013 · 1 comment

Comments

@dlangBugzillaToGithub
Copy link

bearophile_hugs reported this on 2013-03-30T14:06:44Z

Transfered from https://issues.dlang.org/show_bug.cgi?id=9841

CC List

  • greensunny12

Description

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.
@dlangBugzillaToGithub
Copy link
Author

greensunny12 commented on 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.

@LightBender LightBender removed the P4 label Dec 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants