[stdlib] Add `reversed`
Adds an initial implementation of reversed(), for getting a reversed iterator of a range or list.
This isn't meant to be final, since iterators are not fully worked out yet, but it works for now.
Changes:
- Added submodule
/builtin/reversed.mojo - Added function
reversed() - Added trait
ReversibleRange - Implemented
ReversibleRangefor ranges - Added method
__reversed__()inList - Changed
_ListIterto allow for backwards iteration - Added tests for ranges and reversed list iterator
- Fixed original ranges with negative size not passing the new tests
oups i had a premature submit
The fix for ranges having negative length is mostly unnecessary since it never really matters in practice, so that could be changed back to avoid the extra operations.
Just have to remove the edge case section of test_range_len() in test_range.mojo aswell.
_StridedRangeIterator now has a __iter__() method which returns itself.
So reversed(range(...)) behaves as expected with for loops.
Somehow i missed that when testing, because i started off by having reversed() return a non iterator strided range.
that looping test was a little excessive, it makes more sense to check the sums of both ranges.
It occurred to me that i never checked this with the @unroll decorator, so i checked and everything seems to work good
As a follow-up, we can go implement reverse iterator support for
SetandDict, right? I'm happy to create some GitHub issues for that if anyone is interested in working on that.
I'm interested to help on Set and Dict.
ok i added the suggestions, and moved all the reversed range tests into one function (it was kind of split before)
ok i added the suggestions, and moved all the reversed range tests into one function (it was kind of split before)
Merged! Thanks so much for this great contribution — we really appreciate it! 🎉
This is great, thank you!