Bug 14493 – std.range.walkBack too

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P1
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2015-04-24T13:05:00Z
Last change time
2016-04-05T00:22:11Z
Assigned to
nobody
Creator
bearophile_hugs

Comments

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); }
Comment #1 by jack — 2016-04-05T00:22:11Z
This is now covered with std.range.tail