Skip to content

Commit c230f9f

Browse files
authored
iterator: improve type inference for Filter (#59142)
1 parent 1d42e05 commit c230f9f

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

base/iterators.jl

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -534,10 +534,15 @@ filter(flt, itr) = Filter(flt, itr)
534534
function iterate(f::Filter, state...)
535535
y = iterate(f.itr, state...)
536536
while y !== nothing
537-
if f.flt(y[1])
538-
return y
537+
v, s = y
538+
if f.flt(v)
539+
if y isa Tuple{Any,Any}
540+
return (v, s) # incorporate type information that may be improved by user-provided `f.flt`
541+
else
542+
return y
543+
end
539544
end
540-
y = iterate(f.itr, y[2])
545+
y = iterate(f.itr, s)
541546
end
542547
nothing
543548
end

test/iterators.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1201,3 +1201,8 @@ end
12011201
@testset "Iterators docstrings" begin
12021202
@test isempty(Docs.undocumented_names(Iterators))
12031203
end
1204+
1205+
# Filtered list comprehension (`Filter` construct) type inference
1206+
@test Base.infer_return_type((Vector{Any},)) do xs
1207+
[x for x in xs if x isa Int]
1208+
end == Vector{Int}

0 commit comments

Comments
 (0)