Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an iterator from a single element

Tags:

rust

I would like to prepend an element to an iterator. Specifically, I would like to create an iterator that steps through the sequence [2, 3, 5, 7, 9, ...] up to some maximum. The best I've been able to come up with is

range_step_inclusive(2,2,1).chain(range_step_inclusive(3, max, 2))

But the first iterator is kind of a hack to get the single element 2 as an iterator. Is there a more idiomatic way of creating a single-element iterator (or of prepending an element to an iterator)?

like image 496
awelkie Avatar asked Jul 18 '14 17:07

awelkie


People also ask

What does __ ITER __ do in Python?

The __iter__() function returns an iterator for the given object (array, set, tuple, etc. or custom objects). It creates an object that can be accessed one element at a time using __next__() function, which generally comes in handy when dealing with loops.

How do you initialize an iterator?

So you just want to call list. iterator() (which, somewhere inside it, is itself doing new Iterator or something like it and returning that to you). public <T> LinkedList<T> sort(LinkedList<T> list){ Iterator<T> iter = new list. iterator(); while (iter.

How do you iterate over an object in Python?

Iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter() method. It uses the next() method for iteration. next ( __next__ in Python 3) The next method returns the next value for the iterable.

Which of the following methods creates an object which can be iterated one element at a time?

Iterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time. Technically speaking, a Python iterator object must implement two special methods, __iter__() and __next__() , collectively called the iterator protocol.


2 Answers

This is the exact use case of std::iter::once.

Creates an iterator that yields an element exactly once.

This is commonly used to adapt a single value into a chain of other kinds of iteration. Maybe you have an iterator that covers almost everything, but you need an extra special case. Maybe you have a function which works on iterators, but you only need to process one value.

range_step_inclusive is long gone, so let's also use the inclusive range syntax (..=):

iter::once(2).chain((3..=max).step_by(2))
like image 192
CAD97 Avatar answered Sep 19 '22 14:09

CAD97


You can use the Option by-value iterator, into_iter:

Some(2).into_iter().chain((3..).step_by(2))
like image 32
huon Avatar answered Sep 18 '22 14:09

huon