From b99b3390d362050442614f8c85d17aace79a0a1c Mon Sep 17 00:00:00 2001 From: Jeff Bezanson Date: Fri, 27 May 2016 18:30:52 -0400 Subject: [PATCH] use inferred type for empty comprehensions if it is a leaf type this implements the "Steve Johnson compromise": - non-empty comprehensions don't depend on inference at all - in the empty case, we use either Union{} or the inferred type - therefore there is no regression in type precision in cases where we can infer a leaf type --- base/array.jl | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/base/array.jl b/base/array.jl index 0feef9cb3a51b5..18bddbfd9800d8 100644 --- a/base/array.jl +++ b/base/array.jl @@ -237,16 +237,29 @@ function _collect(cont, itr, ::HasEltype, isz::SizeUnknown) return a end +if isdefined(:Base) +@eval function _default_eltype(itrt::ANY) + $(Expr(:meta, :pure)) + try + rt = return_types(first, (itrt,)) + if length(rt) == 1 && isleaftype(rt[1]) + return rt[1] + end + end + return Union{} +end +else _default_eltype(itr::ANY) = Union{} -_default_eltype{I,T}(::Generator{I,Type{T}}) = T +end +_default_eltype{I,T}(::Type{Generator{I,Type{T}}}) = T _collect(c, itr, ::EltypeUnknown, isz::SizeUnknown) = - grow_to!(_similar_for(c, _default_eltype(itr), itr, isz), itr) + grow_to!(_similar_for(c, _default_eltype(typeof(itr)), itr, isz), itr) function _collect(c, itr, ::EltypeUnknown, isz::Union{HasLength,HasShape}) st = start(itr) if done(itr,st) - return _similar_for(c, _default_eltype(itr), itr, isz) + return _similar_for(c, _default_eltype(typeof(itr)), itr, isz) end v1, st = next(itr, st) collect_to_with_first!(_similar_for(c, typeof(v1), itr, isz), v1, itr, st)