Skip to content

Commit 67740a9

Browse files
committed
Improve eltype fallback for rand methods that depend on eltype
1 parent df3004a commit 67740a9

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/common.jl

+16-2
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,23 @@ However, one can provide an array of different element types to store the sample
105105
This method is deprecated and will be removed in an upcoming breaking release.
106106
107107
"""
108-
function Base.eltype(::Type{S}) where {S<:Sampleable}
108+
function Base.eltype(::Type{S}) where {VF<:VariateForm,VS<:Union{Discrete,Continuous},S<:Sampleable{VF,VS}}
109109
Base.depwarn("`eltype(::Type{<:Distributions.Sampleable})` is deprecated and will be removed", :eltype)
110-
return eltype(Base.promote_op(rand, S))
110+
T = Base.promote_op(rand, S)
111+
if T === Union{}
112+
# `T` can be `Union{}` if
113+
# - `rand(::S)` is not defined and/or
114+
# - `rand(::S)` calls `eltype(::S)` or `eltype(::Type{S})` but they are not specialized and fall back to the generic definition here
115+
# (the latter case happens e.g. for non-univariate samplers that only implement `_rand!` and rely on the generic fallback for `rand`)
116+
# In all these cases we return 1) `Int` for `Discrete` samplers and 2) `Float64` for `Continuous` samplers
117+
if VS === Discrete
118+
return Int
119+
elseif VS === Continuous
120+
return Float64
121+
end
122+
else
123+
return eltype(T)
124+
end
111125
end
112126

113127
"""

0 commit comments

Comments
 (0)