Jks Liu
Jks Liu

Reputation: 497

Julia iterates over `Base.Iterators.Reverse`

for i in Iterators.reverse(Iterators.drop([1,2], 1))
    println(i)
end
MethodError: no method matching iterate(::Base.Iterators.Reverse{Base.Iterators.Drop{Array{Int64,1}}})
Closest candidates are:
  iterate(!Matched::LibGit2.GitRevWalker) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.5/LibGit2/src/walker.jl:29
  iterate(!Matched::LibGit2.GitRevWalker, !Matched::Any) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.5/LibGit2/src/walker.jl:29
  iterate(!Matched::Base.EnvDict) at env.jl:119
  ...

Stacktrace:
 [1] top-level scope at ./In[1]:1
 [2] include_string(::Function, ::Module, ::String, ::String) at ./loading.jl:1091

Below version runs correctly

for i in Iterators.reverse(collect(Iterators.drop([1,2], 1)))
    println(i)
end

Why is collect required?

My julia version is 1.5.3, running on WSL2.

Upvotes: 0

Views: 143

Answers (1)

Benoit Pasquier
Benoit Pasquier

Reputation: 3005

The answer is the the error message: collect is required because there is no method matching iterate(::Base.Iterators.Reverse{Base.Iterators.Drop{Array{Int64,1}}}). From the documentation of reverse:

Not all iterator types T support reverse-order iteration. If T doesn't, then iterating over Iterators.reverse(itr::T) will throw a MethodError because of the missing iterate methods for Iterators.Reverse{T}. (To implement these methods, the original iterator itr::T can be obtained from r = Iterators.reverse(itr) by r.itr.)

Upvotes: 1

Related Questions