www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 14493] New: std.range.walkBack too

https://issues.dlang.org/show_bug.cgi?id=14493

          Issue ID: 14493
           Summary: std.range.walkBack too
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: Phobos
          Assignee: nobody puremagic.com
          Reporter: bearophile_hugs eml.cc

Sometimes I need to find the last item of a lazy input range. So I suggest to
add a range like this to Phobos:


import std.stdio, std.range, std.array, std.traits, std.exception;

ForeachType!Range walkBack(Range)(Range r)
if (isInputRange!Range &&
    __traits(compiles, { ForeachType!Range x; x = x; }))
in {
    enforce(!r.empty);
} body {
    static if (__traits(compiles, { return r.back; })) {
        return r.back;
    } else {
        typeof(return) result;
        foreach (element; r)
            result = element;
        return result;
    }
}

void main() {
    auto items1 = [10, 20, 30];
    assert(items1.walkBack == 30);
    //immutable items2 = [10, 20, 30];
    //assert(items2.walkBack == 30);
}

--
Apr 24 2015