Comment #0 by bearophile_hugs — 2015-04-24T13:05:32Z
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);
}