Get iterator "from:to"

Hi, sorry for naive question. I’ve read carefully about iterators ,
but is there a straightforward method to get “from n to m” elements of iterator,
without such as rest(take(iter, m), n)?
NB I use complicated generic iterator, with Combinatorics: multiset_permutation and IterTools: imap, so rest(take(iter, m), n) works but [n:m] not works

You can still use the n:m syntax, even when neither n nor m is known at compile time:

julia> f(n, m) = n:m
f (generic function with 1 method)

julia> collect(f(7, 9))
3-element Vector{Int64}:
 7
 8
 9

I think the approach you mentioned is the only approach that works with generic iterators. However, you should use drop instead of rest.

julia> using .Iterators: drop, take

julia> m_to_n(itr, m, n) = drop(take(itr, n), m-1);

julia> itr = m_to_n(1:10, 3, 8);

julia> collect(itr)
6-element Vector{Int64}:
 3
 4
 5
 6
 7
 8
2 Likes

Well, thank you for evidence, sorry for my bad English! “Generic” :sweat_smile:
How do you think, which combination of drop, take, rest be most efficient for big (with ~10^6 members) iterator?

The drop and take combination should be reasonably efficient. You should generally avoid using Iterators.rest since it relies on understanding how the internal state variable of the iterator is used, which is normally an implementation detail that is not exposed as part of the interface for a given iterator.

1 Like

Off-topic: Is there a reason to prefer .Iterators over Base.Iterators?

Not really. I guess it’s just a matter of taste.

1 Like