[Issue 4535] New: std.range could have a takeWhile!pred(range) function

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Jul 30 02:49:28 PDT 2010


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

           Summary: std.range could have a takeWhile!pred(range) function
           Product: D
           Version: D2
          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-07-30 11:49:25 CEST ---
takeWhile!predicate(range) is a very useful function, that lazily produces
elements of a range, as long as a predicate holds for the produced elements.

Usage example:
----
auto small = takeWhile!"a<5"([0,1,2,3,4,5,6,7,6,5,4,3,2,1,0]);
assert(equal(small, [0,1,2,3,4,5]);
----

That's different from filter!predicate(range) that would return _all_ elements
in the range that satisfy the predicate.

Possible code for this follow:


import std.functional: unaryFun;
import std.range;


struct TakeWhile(alias pred, R)
if (isInputRange!R && is(typeof(!unaryFun!pred(ElementType!R.init)) == bool))
{
    R _range;

    bool empty() @property
    {
        return _range.empty || !(unaryFun!pred(_range.front));
    }

    ElementType!R front() @property
    {
        return _range.front;
    }

    TakeWhile save() @property
    {
        return this;
    }

    void popFront()
    {
        _range.popFront;
    }
}

TakeWhile!(pred, R) takeWhile(alias pred, R)(R range) if (isInputRange!R)
{
    return TakeWhile!(pred,R)(range);
}

unittest
{
    auto arr = [0,1,2,3,4,3,2,1,0];

    // With 'string functions'
    assert(equal( takeWhile!"a<3"(arr), [0,1,2])); // standard case
    assert(equal( takeWhile!"a<10"(arr), arr));    // predicate true for all
elements
    assert(takeWhile!"a<0"(arr).empty);            // predicate false from the
beginning
    assert(takeWhile!"a!=0"(arr).empty);           // predicate false for the
first element

    // With a standard function
    bool foo(int i) { return i != 4;}
    assert(equal( takeWhile!foo(arr), [0,1,2,3]));
}

-- 
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