diff --git a/src/StructUtils.jl b/src/StructUtils.jl index 6ba1da8..208d921 100644 --- a/src/StructUtils.jl +++ b/src/StructUtils.jl @@ -168,7 +168,7 @@ initialize(st::StructStyle, T::Type, @nospecialize(source)) = function initialize(st::StructStyle, ::Type{A}, source) where {A<:AbstractArray} if ndims(A) > 1 - dims = discover_dims(st, source) + dims = discover_dims(st, source, ndims(A)) return A(undef, dims) else return A(undef, 0) @@ -660,12 +660,16 @@ end # VERSION < v"1.10" # "[[[1.0],[2.0]]]" => (1, 2, 1) # "[[[1.0,2.0]]]" => (2, 1, 1) # length of innermost array is 1st dim -function discover_dims(style, x) +function discover_dims(style, x, ndims::Int) @assert arraylike(style, x) len = applylength(x) + if ndims == 1 + return (len,) + end + ret = ( applyeach(x) do _, v - return arraylike(style, v) ? EarlyReturn(discover_dims(style, v)) : EarlyReturn(()) + return arraylike(style, v) ? EarlyReturn(discover_dims(style, v, ndims - 1)) : EarlyReturn(()) end )::EarlyReturn return (ret.value..., len) @@ -680,7 +684,7 @@ end function (f::MultiDimClosure{S,A})(i::Int, val) where {S,A} f.dims[f.cur_dim[]] = i - if arraylike(f.style, val) + if arraylike(f.style, val) && f.cur_dim[] > 1 f.cur_dim[] -= 1 st = applyeach(f, f.style, val) f.cur_dim[] += 1 diff --git a/test/runtests.jl b/test/runtests.jl index 38357df..b84cbac 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -288,6 +288,22 @@ end # fill slice [:, :, 2] from second slab [[3,4]] exp3[:, :, 2] = reshape([3,4], 2, 1) @test x3 == exp3 + + # Jagged nested vectors (Vector of Vectors) + jagged = [[1, 2], [3, 4, 5], [6]] + result = StructUtils.make(Vector{Vector{Int}}, jagged) + @test result == jagged + + # Multi-dimensional case with jagged inner vectors + vv_jagged = [[[1, 2], [3]], [[4, 5, 6], [7, 8]]] + result_md = StructUtils.make(Array{Vector{Int}, 2}, vv_jagged) + + md_jagged = Array{Vector{Int}}(undef, 2, 2) + md_jagged[1, 1] = [1, 2] + md_jagged[2, 1] = [3] + md_jagged[1, 2] = [4, 5, 6] + md_jagged[2, 2] = [7, 8] + @test result_md == md_jagged end @testset "@nonstruct macro" begin