Skip to content

Commit 52e98c9

Browse files
Merge pull request #514 from JoshuaLampert/patch1
Add support for undef initializer in `ArrayPartition`
2 parents c41e5d0 + 032b806 commit 52e98c9

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

src/array_partition.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,15 @@ end
3131
@inline ArrayPartition(f::F, N) where {F <: Function} = ArrayPartition(ntuple(f, Val(N)))
3232
ArrayPartition(x...) = ArrayPartition((x...,))
3333

34+
function (::Type{ArrayPartition{T, S}})(::UndefInitializer, n::Integer) where {T, S <: Tuple}
35+
if length(S.parameters) != 1
36+
throw(ArgumentError("ArrayPartition{T,S}(undef, n) is only supported for a single partition"))
37+
end
38+
part_type = S.parameters[1]
39+
part = part_type(undef, n)
40+
return ArrayPartition{T, S}((part,))
41+
end
42+
3443
function ArrayPartition(x::S, ::Type{Val{copy_x}} = Val{false}) where {S <: Tuple, copy_x}
3544
T = promote_type(map(recursive_bottom_eltype, x)...)
3645
if copy_x

test/partitions_test.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,15 @@ using RecursiveArrayTools, Test, Statistics, ArrayInterface, Adapt
33
@test length(ArrayPartition()) == 0
44
@test isempty(ArrayPartition())
55

6+
# Test undef initializer for single-partition ArrayPartition
7+
p_undef = ArrayPartition{Float64, Tuple{Vector{Float64}}}(undef, 10)
8+
@test p_undef isa ArrayPartition{Float64, Tuple{Vector{Float64}}}
9+
@test length(p_undef) == 10
10+
@test length(p_undef.x) == 1
11+
@test length(p_undef.x[1]) == 10
12+
# Test that multi-partition throws error
13+
@test_throws ArgumentError ArrayPartition{Float64, Tuple{Vector{Float64}, Vector{Float64}}}(undef, 10)
14+
615
A = (rand(5), rand(5))
716
p = ArrayPartition(A)
817
@inferred p[1]

0 commit comments

Comments
 (0)