Skip to content

Commit 3e706b4

Browse files
authored
ensure type in array convert (#237)
1 parent 5be668f commit 3e706b4

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

src/FillArrays.jl

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,27 @@ Fill{T,0}(x::T, ::Tuple{}) where T = Fill{T,0,Tuple{}}(x, ()) # ambiguity fix
148148
@inline axes(F::Fill) = F.axes
149149
@inline size(F::Fill) = map(length, F.axes)
150150

151+
"""
152+
getindex_value(F::AbstractFill)
153+
154+
Return the value that `F` is filled with.
155+
156+
# Examples
157+
158+
```jldoctest
159+
julia> f = Ones(3);
160+
161+
julia> FillArrays.getindex_value(f)
162+
1.0
163+
164+
julia> g = Fill(2, 10);
165+
166+
julia> FillArrays.getindex_value(g)
167+
2
168+
```
169+
"""
170+
getindex_value
171+
151172
@inline getindex_value(F::Fill) = F.value
152173

153174
AbstractArray{T}(F::Fill{V,N}) where {T,V,N} = Fill{T}(convert(T, F.value)::T, F.axes)
@@ -156,7 +177,12 @@ AbstractFill{T}(F::AbstractFill) where T = AbstractArray{T}(F)
156177

157178
copy(F::Fill) = Fill(F.value, F.axes)
158179

159-
""" Throws an error if `arr` does not contain one and only one unique value. """
180+
"""
181+
unique_value(arr::AbstractArray)
182+
183+
Return `only(unique(arr))` without intermediate allocations.
184+
Throws an error if `arr` does not contain one and only one unique value.
185+
"""
160186
function unique_value(arr::AbstractArray)
161187
if isempty(arr) error("Cannot convert empty array to Fill") end
162188
val = first(arr)
@@ -438,7 +464,8 @@ end
438464

439465

440466
## Array
441-
Base.Array{T,N}(F::AbstractFill{V,N}) where {T,V,N} = fill(convert(T, getindex_value(F)), size(F))
467+
Base.Array{T,N}(F::AbstractFill{V,N}) where {T,V,N} =
468+
convert(Array{T,N}, fill(convert(T, getindex_value(F)), size(F)))
442469

443470
# These are in case `zeros` or `ones` are ever faster than `fill`
444471
for (Typ, funcs, func) in ((:Zeros, :zeros, :zero), (:Ones, :ones, :one))
@@ -449,7 +476,7 @@ end
449476

450477
# temporary patch. should be a PR(#48895) to LinearAlgebra
451478
Diagonal{T}(A::AbstractFillMatrix) where T = Diagonal{T}(diag(A))
452-
function convert(::Type{T}, A::AbstractFillMatrix) where T<:Diagonal
479+
function convert(::Type{T}, A::AbstractFillMatrix) where T<:Diagonal
453480
checksquare(A)
454481
isdiag(A) ? T(A) : throw(InexactError(:convert, T, A))
455482
end

0 commit comments

Comments
 (0)