Skip to content

Commit

Permalink
use inferred type instead of Union{} for empty comprehensions
Browse files Browse the repository at this point in the history
  • Loading branch information
JeffBezanson authored and mfasi committed Sep 5, 2016
1 parent 89bb3ca commit 9f997bd
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 10 deletions.
15 changes: 8 additions & 7 deletions base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -283,14 +283,10 @@ function _collect(cont, itr, ::HasEltype, isz::SizeUnknown)
end

if isdefined(Core, :Inference)
function _default_eltype(itrt::ANY)
rt = Core.Inference.return_type(first, Tuple{itrt})
return isleaftype(rt) ? rt : Union{}
end
_default_eltype(itrt::ANY) = Core.Inference.return_type(first, Tuple{itrt})
else
_default_eltype(itr::ANY) = Union{}
_default_eltype(itr::ANY) = Any
end
_default_eltype{I,T}(::Type{Generator{I,Type{T}}}) = T

_array_for(T, itr, ::HasLength) = Array{T,1}(Int(length(itr)::Integer))
_array_for(T, itr, ::HasShape) = similar(Array{T}, indices(itr))
Expand Down Expand Up @@ -354,7 +350,12 @@ function collect_to!{T}(dest::AbstractArray{T}, itr, offs, st)
return dest
end

function grow_to!(dest, itr, st = start(itr))
function grow_to!(dest, itr)
out = grow_to!(similar(dest,Union{}), itr, start(itr))
return isempty(out) ? dest : out
end

function grow_to!(dest, itr, st)
T = eltype(dest)
while !done(itr, st)
el, st = next(itr, st)
Expand Down
11 changes: 9 additions & 2 deletions base/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -380,11 +380,18 @@ end

dict_with_eltype{K,V}(kv, ::Type{Tuple{K,V}}) = Dict{K,V}(kv)
dict_with_eltype{K,V}(kv, ::Type{Pair{K,V}}) = Dict{K,V}(kv)
dict_with_eltype(kv, t) = grow_to!(Dict{Union{},Union{}}(), kv)
dict_with_eltype{K,V}(::Type{Pair{K,V}}) = Dict{K,V}()
dict_with_eltype(::Type) = Dict()
dict_with_eltype(kv, t) = grow_to!(dict_with_eltype(_default_eltype(typeof(kv))), kv)

# this is a special case due to (1) allowing both Pairs and Tuples as elements,
# and (2) Pair being invariant. a bit annoying.
function grow_to!{K,V}(dest::Associative{K,V}, itr, st = start(itr))
function grow_to!(dest::Associative, itr)
out = grow_to!(similar(dest, Pair{Union{},Union{}}), itr, start(itr))
return isempty(out) ? dest : out
end

function grow_to!{K,V}(dest::Associative{K,V}, itr, st)
while !done(itr, st)
(k,v), st = next(itr, st)
if isa(k,K) && isa(v,V)
Expand Down
2 changes: 1 addition & 1 deletion base/set.jl
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Set() = Set{Any}()
Set(itr) = Set{eltype(itr)}(itr)
function Set(g::Generator)
T = _default_eltype(typeof(g))
T === Union{} && return grow_to!(Set{T}(), g)
(isleaftype(T) || T === Union{}) || return grow_to!(Set{T}(), g)
return Set{T}(g)
end

Expand Down

0 comments on commit 9f997bd

Please sign in to comment.