Skip to content

Commit

Permalink
improved eltype for flatten with tuple argument (#55946)
Browse files Browse the repository at this point in the history
We have always had
```
julia> t = (Int16[1,2], Int32[3,4]); eltype(Iterators.flatten(t))
Any
```
With this PR, the result is `Signed` (`promote_typejoin` applied to the
element types of the tuple elements).

The same applies to `NamedTuple`:
```
julia> nt = (a = [1,2], b = (3,4)); eltype(Iterators.flatten(nt))
Any     # old
Int64   # new
```
  • Loading branch information
matthias314 authored Oct 28, 2024
1 parent e802eff commit 4c076c8
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 1 deletion.
3 changes: 2 additions & 1 deletion base/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ end
import .Base:
first, last,
isempty, length, size, axes, ndims,
eltype, IteratorSize, IteratorEltype,
eltype, IteratorSize, IteratorEltype, promote_typejoin,
haskey, keys, values, pairs,
getindex, setindex!, get, iterate,
popfirst!, isdone, peek, intersect
Expand Down Expand Up @@ -1213,6 +1213,7 @@ 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))...)
eltype(::Type{Flatten{Tuple{}}}) = eltype(Tuple{})
IteratorEltype(::Type{Flatten{I}}) where {I} = _flatteneltype(I, IteratorEltype(I))
IteratorEltype(::Type{Flatten{Tuple{}}}) = IteratorEltype(Tuple{})
Expand Down
2 changes: 2 additions & 0 deletions test/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,8 @@ end
@test collect(flatten(Any[flatten(Any[1:2, 6:5]), flatten(Any[6:7, 8:9])])) == Any[1,2,6,7,8,9]
@test collect(flatten(Any[2:1])) == Any[]
@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 length(flatten(zip(1:3, 4:6))) == 6
@test length(flatten(1:6)) == 6
@test collect(flatten(Any[])) == Any[]
Expand Down

0 comments on commit 4c076c8

Please sign in to comment.