Skip to content

Make blocks(randn(2, 2))[1, 1] return the original array #403

Open
@mtfishman

Description

@mtfishman

Currently, blocks has this behavior:

julia> using BlockArrays

julia> blocks(randn(2, 2))[1, 1]
2×2 view(::Matrix{Float64}, BlockSlice(Block(1),Base.OneTo(2)), BlockSlice(Block(1),Base.OneTo(2))) with eltype Float64:
 -1.50189  2.04898
  1.76046  0.382146

julia> using Pkg; Pkg.status("BlockArrays")
Status `~/Simons Foundation Dropbox/Matthew Fishman/Documents/workdir/BlockArrays.jl/Project.toml`
  [8e7c35d0] BlockArrays v1.0.1

I think it could be nice to have it return the input array instead of a view when it can be known from the type of the original array that it only has one block. Working with the view, while not too bad, is a bit more complicated than just working with the original array.

A design could be an alternative type to BlocksView:

struct OneBlockView{T,N,A<:AbstractArray{T,N}} <: AbstractArray{T,N}
    array::A
end
Base.size(a::OneBlockView) = ntuple(Returns(1), ndims(a))
function Base.getindex(a::OneBlockView{T,N}, i::Vararg{Int,N}) where {N}
    @boundscheck checkbounds(a, i...)
    return a.array
end
function Base.setindex!(a::OneBlockView{T,N}, b, i::Vararg{Int,N}) where {N}
    @boundscheck checkbounds(a, i...)
    copyto!(a.array, b)
    return a
end

blocks(a::Array) = OneBlockView(a)

It may warrant having an is_blocked trait (say to detect if wrapped arrays are blocked or not) but I think that is a different story.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions