[Issue 3872] New: std.algorithm.filter could become bidirectional if its input range is bidir

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Mar 4 05:56:07 PST 2010


http://d.puremagic.com/issues/show_bug.cgi?id=3872

           Summary: std.algorithm.filter could become bidirectional if its
                    input range is bidir
           Product: D
           Version: 2.040
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: Phobos
        AssignedTo: nobody at puremagic.com
        ReportedBy: philippe.sigaud at gmail.com


--- Comment #0 from Philippe Sigaud <philippe.sigaud at gmail.com> 2010-03-04 14:56:05 CET ---
std.algorithm.filter returns a forward range. This could become a bidirectional
range if its input range is also a bidirectional range. That way, filter can
fed to more algorithms.

Obviously, it cannot in general become a random-access range or define a
length... Too bad.

Possible code follow:

struct Filter(alias pred, Range) if (isInputRange!(Range))
{
    Range _input;

    this(Range r)
    {
        _input = r;
        while (!_input.empty && !pred(_input.front)) _input.popFront;
        static if (isBidirectionalRange!Range)
            while (!_input.empty && !pred(_input.back)) _input.popBack;
    }

    ref Filter opSlice()
    {
        return this;
    }

    bool empty() { return _input.empty; }
    void popFront()
    {
        do
        {
            _input.popFront;
        } while (!_input.empty && !pred(_input.front));
    }

    ElementType!(Range) front() { return _input.front;}

    static if (isBidirectionalRange!Range) {
        void popBack()
        {
            do
            {
                _input.popBack;
            } while (!_input.empty && !pred(_input.back));
        }

        ElementType!(Range) back() { return _input.back;}
    }
}

unittest
{
    auto r = [0,1,2,3,4];
    auto f = filter!"a%2==0"(r);
    assert(equal(retro(f), [4,2,0][])); // f is a bidirectional range
}

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list