Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix eltype of flatten of tuple with non-2 length #56802

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix eltype of flatten of tuple with non-2 length
In 4c076c8, eltype of flatten of tuple was improved by computing a refined
eltype at compile time. However, this implementation only worked for length-2
tuples, and errored for all others.
Generalize this to all tuples.
  • Loading branch information
jakobnissen committed Dec 11, 2024
commit aeb3473e2eba4df4537d33f852337191c44b8acc
16 changes: 15 additions & 1 deletion base/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1202,7 +1202,21 @@ julia> [(x,y) for x in 0:1 for y in 'a':'c'] # collects generators involving It
flatten(itr) = Flatten(itr)

eltype(::Type{Flatten{I}}) where {I} = eltype(eltype(I))
eltype(::Type{Flatten{I}}) where {I<:Union{Tuple,NamedTuple}} = promote_typejoin(map(eltype, fieldtypes(I))...)

# For tuples, we statically know the element type of each index, so we can compute
# this at compile time.
Base.@assume_effects :foldable function eltype(
::Type{Flatten{I}}
) where {I<:Union{Tuple,NamedTuple}}
T = Union{}
for i in fieldtypes(I)
T = Base.promote_typejoin(T, eltype(i))
T === Any && return Any
jakobnissen marked this conversation as resolved.
Show resolved Hide resolved
end
T
end

promote_typejoin(map(eltype, fieldtypes(I))...)
eltype(::Type{Flatten{Tuple{}}}) = eltype(Tuple{})
IteratorEltype(::Type{Flatten{I}}) where {I} = _flatteneltype(I, IteratorEltype(I))
IteratorEltype(::Type{Flatten{Tuple{}}}) = IteratorEltype(Tuple{})
Expand Down
3 changes: 3 additions & 0 deletions test/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,9 @@ end
@test eltype(flatten(UnitRange{Int8}[1:2, 3:4])) == Int8
@test eltype(flatten(([1, 2], [3.0, 4.0]))) == Real
@test eltype(flatten((a = [1, 2], b = Int8[3, 4]))) == Signed
@test eltype(flatten((Int[], Nothing[], Int[]))) == Union{Int, Nothing}
@test eltype(flatten((String[],))) == String
@test eltype(flatten((Int[], UInt[], Int8[],))) == Integer
@test length(flatten(zip(1:3, 4:6))) == 6
@test length(flatten(1:6)) == 6
@test collect(flatten(Any[])) == Any[]
Expand Down
Loading