Skip to content

Commit 258c507

Browse files
aviateskKristofferC
authored andcommitted
iterator: improve type inference for Filter (#59142)
1 parent 02e3bb9 commit 258c507

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
@@ -1142,3 +1142,8 @@ end
11421142
@testset "Iterators docstrings" begin
11431143
@test isempty(Docs.undocumented_names(Iterators))
11441144
end
1145+
1146+
# Filtered list comprehension (`Filter` construct) type inference
1147+
@test Base.infer_return_type((Vector{Any},)) do xs
1148+
[x for x in xs if x isa Int]
1149+
end == Vector{Int}

0 commit comments

Comments
 (0)