itertools icon indicating copy to clipboard operation
itertools copied to clipboard

Feature: add circular_tuple_windows

Open ed-bassett opened this issue 5 years ago • 1 comments

The tuple_windows function is very useful, but I've found myself using something like the following quite often — it's very useful when processing anything circular in nature, but represented as a Vec (or anything iter):

something.iter().cycle().tuple_windows().take(self.len())

Where tuple_windows::<(_,_,_)> for [1,2,3,4] would iterate through (1,2,3) & (2,3,4), circular_tuple_windows::<(_,_,_)> would iterate through (1,2,3), (2,3,4), (3,4,1) & (4,1,2), meaning that every element would be iterated through, having access to the previous and next elements in a circular structure.

I tried to add just for my project, but I think I would need to use itertools::tuple_impl::TupleCollect, which is private. But I figured it would likely be useful for other too, so thought I'd suggest the feature.

ed-bassett avatar Jun 15 '19 02:06 ed-bassett

I don't think this should be implemented with cycle(), because it requires the iterator to be clonable, which is imo excessive (the method doesn't work with e.g. stdin Lines iterator). Storing the first n - 1 items in a buffer (which requires only that the iterated items are clonable, instead of the iterator itself) seems to me like a better solution.

EDIT: I see that this solution was already proposed in the PR to remove another constraint. It looks better to me than the current merged version. :)

MatejKafka avatar Oct 17 '21 22:10 MatejKafka