Proper definition of eltype for custom iterator

I would write it as:

struct Squares{T <: Real}
    count::Int
end

Base.iterate(s::Squares{T}, state=1) where {T} = state > s.count ? nothing : (T(state^2), state+1)
Base.length(s::Squares) = s.count
Base.eltype(::Type{Squares{T}}) where {T} = T

And the code you executed would be written as:

for i in Squares{UInt8}(4) println(i) end

collect(Squares{Rational{Int64}}(3))

9 in Squares{Float32}(3)
2 Likes