Skip to content

broadcast for AbstractArray types #17533

@ettersi

Description

@ettersi

Consider the following code:

immutable MyArray{T,N} <: AbstractArray{T,N}
    a::Array{T,N}
end
Base.linearindexing{T,N}(::Type{MyArray{T,N}}) = Base.LinearFast()
Base.size(m::MyArray) = size(m.a)
Base.getindex(m::MyArray, i::Int) = m.a[i]
Base.setindex!(m::MyArray, v, i::Int) = m.a[i] = v
Base.similar{T,N}(::MyArray, ::Type{T}, dims::NTuple{N,Int}) = MyArray(Array(T,dims))

Thanks to the AbstractArray magic, these 8 lines should define a type with the same interface as Array. This is however not the case:

julia> typeof(MyArray([1]).*MyArray([1]))
Array{Int64,1}

The problem originates from the following definition of broadcast():

broadcast(f, As...) = 
    broadcast!(
        f, 
        Array(promote_eltype(As...), broadcast_shape(As...)),
        As...
    )

I suggest changing this definition to:

broadcast(f, As...) = 
    broadcast!(
        f, 
        similar(first(As), promote_eltype(As...), broadcast_shape(As...)),
        As...
    )

This would fix the above problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    broadcastApplying a function over a collection

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions