Empty iterator

a function of mine returns an iterator. in some cases, i want to return an empty iterator, but one that is efficient and typed. so i came up with this little thing

struct Empty{T} end
Base.iteratorsize(::Type{<:Empty}) = Base.HasLength()
Base.eltype(::Type{Empty{T}}) where T = T
Base.start(::Empty) = nothing
Base.done(::Empty, st) = true
Base.length(::Empty) = 0

empty(T) = Empty{T}()

but i’m wondering if there is some neat built-in way to do this

1 Like

Wouldn’t an empty array serve the same purpose? You can construct it with Array{T}(0). But it might have more overhead.

array was my first thought, but since Julia is rich in specialized enumerators, such a type seems to make sense.

In a few situations (e.g., tuples or StaticArrays), you can tell via the type system that a container is empty; in such cases, having a special type for empty iteration might make sense.

But in most cases you have to check a value to determine whether the container is empty (e.g., isempty(c) which returns a boolean value). In such cases, you probably don’t want to use a distinct type to encode an empty iterator, because that will make your method that returns an iterator non-inferrable. As long as you can write an efficient done method for your iterator type, you probably won’t notice the overhead from iterating over empty iterators.

5 Likes

How about simply 1:0 if the type T is Int? It has no overhead afaik.