Bug 6035 – std.algorithm.reversed()

Status
RESOLVED
Resolution
INVALID
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2011-05-18T18:20:00Z
Last change time
2011-05-19T04:28:47Z
Assigned to
nobody
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2011-05-18T18:20:56Z
std.algorithm has a reverse() function: http://www.digitalmars.com/d/2.0/phobos/std_algorithm.html#reverse (reverse() returns void, this is correct and right, because it works in-place. Returning the reversed array is the wrong thing to do.) reverse duplicates what the array reverse attribute performs: auto a = [1, 2, 3]; a.reverse; But in functional-style code I want to create expressions, so I can't use a function (a procedure) that returns void: foreach (x; reversed(foo(array1))) {... And sometimes I don't to work-in place, I need a reversed view of something that I don't want to modify. So I suggest to introduce a std.algorithm.reversed() (or std.range.reversed()) function, that lazily yieds the reversed items, as in Python: >>> a ['a', 'b', 'c', 'd'] >>> a = [1, 2, 3] >>> reversed(a) <listreverseiterator object at 0x01A02910> >>> list(reversed(a)) [3, 2, 1] >>> a [1, 2, 3] Returning a copy is also useful for immutable arrays, and generally it fits better in functional-style programming. See also enhancement issue 5076 that's about sorted(), another function usable in expressions, that doesn't modify the original iterable.
Comment #1 by bearophile_hugs — 2011-05-18T18:32:43Z
For an usage example see issue 6034
Comment #2 by kennytm — 2011-05-18T21:10:13Z
std.range.retro ?
Comment #3 by bearophile_hugs — 2011-05-19T04:28:47Z
(In reply to comment #2) > std.range.retro ? Sorry for the noise.