Skip to content

Commit 04862d2

Browse files
committed
slightly re-organize constructors
1 parent 3935364 commit 04862d2

File tree

1 file changed

+26
-12
lines changed

1 file changed

+26
-12
lines changed

src/sparsearraydok.jl

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -28,31 +28,45 @@ struct SparseArrayDOK{T,N,F} <: AbstractSparseArray{T,N}
2828
end
2929
end
3030

31-
# undef constructors
32-
function SparseArrayDOK{T}(
31+
## constructors with T and N
32+
# -> make SparseMatrix{T}(undef, ...) work
33+
function SparseArrayDOK{T,N}(
3334
::UndefInitializer, dims::Dims, getunstoredindex=default_getunstoredindex
34-
) where {T}
35-
all((0), dims) || throw(ArgumentError("Invalid dimensions: $dims"))
36-
N = length(dims)
35+
) where {T,N}
36+
(length(dims) == N && all((0), dims)) ||
37+
throw(ArgumentError("Invalid dimensions: $dims"))
3738
F = typeof(getunstoredindex)
3839
return SparseArrayDOK{T,N,F}(undef, dims, getunstoredindex)
3940
end
40-
function SparseArrayDOK{T}(::UndefInitializer, dims::Int...) where {T}
41-
return SparseArrayDOK{T}(undef, dims)
41+
42+
## constructors with T
43+
function SparseArrayDOK{T}(::UndefInitializer, dims::Dims{N}, unstored...) where {T,N}
44+
return SparseArrayDOK{T,N}(undef, dims, unstored...)
45+
end
46+
47+
function SparseArrayDOK{T}(::UndefInitializer, dims::Vararg{Int,N}) where {T,N}
48+
return SparseArrayDOK{T,N}(undef, dims)
4249
end
4350

44-
# checked constructor from data: use `setindex!` to validate input
45-
# does not take ownership of `storage`!
46-
function SparseArrayDOK(
47-
storage::Union{AbstractDictionary{I,T},AbstractDict{I,T}}, dims::Dims{N}, unstored...
48-
) where {N,I<:Union{Int,CartesianIndex{N}},T}
51+
# checked constructor from data: use `setindex!` to validate/convert input
52+
function SparseArrayDOK{T}(
53+
storage::Union{AbstractDictionary,AbstractDict}, dims::Dims, unstored...
54+
) where {T}
4955
A = SparseArrayDOK{T}(undef, dims, unstored...)
5056
for (i, v) in pairs(storage)
5157
A[i] = v
5258
end
5359
return A
5460
end
5561

62+
## constructors without type parameters
63+
function SparseArrayDOK(
64+
storage::Union{AbstractDictionary,AbstractDict}, dims::Dims, unstored...
65+
)
66+
T = valtype(storage)
67+
return SparseArrayDOK{T}(storage, dims, unstored...)
68+
end
69+
5670
function set_getunstoredindex(a::SparseArrayDOK, f)
5771
@set a.getunstoredindex = f
5872
return a

0 commit comments

Comments
 (0)