UnionArrays.jl
UnionArrays.UnionArrays
โ ModuleUnionArrays: storage-agnostic array type with Union
elements
UnionArrays.jl provides an array type with Union
element types that is generic over the data storage type.
julia> using UnionArrays
julia> xs = UnionVector(undef, Vector, Union{Float32,Tuple{},UInt8}, 3);
julia> fill!(xs, ());
julia> xs[1]
()
julia> xs[2] = 1.0f0;
julia> xs[3] = UInt8(2);
julia> collect(xs)
3-element Vector{Union{Tuple{}, Float32, UInt8}}:
()
1.0f0
0x02
For example, it can be used for bringing Union
element types to GPU:
julia> using CUDA
julia> xs = UnionVector(undef, CuVector, Union{Float32,Nothing}, 3);
julia> fill!(xs, nothing);
Packages like Transducers.jl and Folds.jl support computations with UnionArray
s on GPU:
julia> using Folds, FoldsCUDA
julia> Folds.all(==(nothing), xs)
true
julia> CUDA.@allowscalar begin
xs[2] = 1.0f0
xs[3] = 2.0f0
end;
julia> Folds.sum(x -> x === nothing ? 0.0f0 : x, xs; init = 0.0f0)
3.0f0
UnionArrays.Abstract.UnionArray
โ TypeUnionArray{T, N}
UnionVector{T}
UnionMatrix{T}
UnionArray
stores heterogeneous elements without indirections (which would happen in Array{Any}
).
Examples
julia> using UnionArrays
julia> xs = UnionVector(Any[UInt8(1), 2.0, (a=1, b=2)]);
julia> xs[1]
0x01
julia> xs[2]
2.0
julia> xs[3]
(a = 1, b = 2)
julia> xs[1] = (a=3, b=4);
julia> xs[1]
(a = 3, b = 4)
julia> M = reshape(xs, (1, :)) :: UnionMatrix;
julia> M[1, 1]
(a = 3, b = 4)