Hey guys,
I just ran into a problem where I had a runtime issue where some code tried to iterate over a non-iterable type and then I ran into the definition in the standard library.
struct Enumerate{I}
itr::I
end
enumerate(iter) = Enumerate(iter)
function iterate(e::Enumerate, state=(1,))
i, rest = state[1], tail(state)
n = iterate(e.itr, rest...)
n === nothing && return n
(i, n[1]), (i+1, n[2])
end
If I understand that correctly Enumerate is defined for every type (even though the name I
implies that the type should be iterable), which would be mathematically incorrect.
It only fails at runtime when the iterate
function isn’t defined for that type. I know that in Rust iterate is only defined for types that implement the iterable trait and even in python + mypy you can check if a class has defined __iter__
, otherwise you will get an error even before compile time. So why is Enumerate
defined in such a way and how can I define a method to only accept types that implement certain methods?
Thanks and cheers!