Hi all,
I am following the manual to learn to define a customized iterator, but couldn’t figure out what I did wrong.
If I use for loop, it gave error “MethodError: no method matching length”.
If I use while loop, it gave error “MethodError: no method matching iterate(::Nothing)”.
Could someone please point me where the problem is?
Thanks!
struct Farey_Sequence
N :: Int
descending :: Bool
Farey_Sequence(n; descending = false) = new(n, descending)
end
function Base.iterate(f :: Farey_Sequence) :: Union{Nothing, Tuple{Rational{Int}, NTuple{4, Int}}}
if f.descending
a, b, c, d = 1, 1, f.N - 1, f.N
else
a, b, c, d = 0, 1, 1, f.N
end
a // b, (a, b, c, d)
end
function Base.iterate(f :: Farey_Sequence, state :: NTuple{4, Int}) :: Union{Nothing, Tuple{Rational{Int}, NTuple{4, Int}}}
a, b, c, d = state
if (c <= f.N && !f.descending) || (a > 0 && f.descending)
k = (f.N + b) ÷ d
(a, b, c, d) = (c, d, k * c - a, k * d - b)
return a // b, (a, b, c, d)
else
return nothing
end
end