Iterators: take filter countfrom

Is there a more compact form to write

n -> Iterators.take(Iterators.filter(predicate, Iterators.countfrom(1)), n) ?

Edit: The wording of my question has obviously given the impression that I am only concerned with syntactic sugar. Firstly I wanted to make sure that I had not overlooked an existing iterator. But secondly, to me this iterator seems to describe a very common task. Therefore I wonder whether it is worth building it explicitly, and if so, look if someone already has such a solution in the drawer.

If not, I will give bennedich’s solution the preference.

That looks pretty legible to me. I guess you could import the functions from Iterators if you wanted to:

import Base.Iterators: take, filter, countfrom

n -> take(filter(predicate, countfrom(1)), n)
3 Likes

In addition to what @bennedich wrote, I often find it more readable to give a name to interim values, eg

function first_filtered_n(predicate, n)
    filtered = Iterators.filter(predicate, Iterators.countfrom(1))
    Iterators.take(filtered, n)
end
1 Like

You can use Query.jl’s piping syntax. Which some people love, and some hate :slight_smile:

using Query

n -> Iterators.countfrom(1) |> @filter(predicate(_)) |> @take(n)
3 Likes