www.digitalmars.com         C & C++   DMDScript  

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

reply d-bugmail puremagic.com writes:
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 puremagic.com
        ReportedBy: philippe.sigaud gmail.com


--- Comment #0 from Philippe Sigaud <philippe.sigaud 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: -------
Mar 04 2010
parent d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=3872


David Simcha <dsimcha yahoo.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |RESOLVED
                 CC|                            |dsimcha yahoo.com
         Resolution|                            |FIXED


--- Comment #1 from David Simcha <dsimcha yahoo.com> 2010-06-30 19:58:43 PDT ---
Fixed SVN.

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