Skip to content

Instantly share code, notes, and snippets.

@cossio
Created July 11, 2018 11:38
Show Gist options
  • Save cossio/9512f51a25388ed66f6676171d027f78 to your computer and use it in GitHub Desktop.
Save cossio/9512f51a25388ed66f6676171d027f78 to your computer and use it in GitHub Desktop.
A tensor of zeros (Julia)
"A tensor of zeros"
struct ZeroTensor{T <: Number, N} <: AbstractArray{T,N}
dims::NTuple{N,Int}
function ZeroTensor{T,N}(dims::Vararg{Integer,N}) where {T <: Number, N}
all(dims .≥ 0) || error("invalid ZeroTensor dimensions")
new(dims)
end
end
ZeroTensor(T::DataType, dims::Vararg{Integer,N}) where N = ZeroTensor{T,N}(dims...)
ZeroTensor(dims::Vararg{Integer,N}) where {N} = ZeroTensor{Float64,N}(dims...)
Base.size(a::ZeroTensor) = a.dims
function Base.getindex(a::ZeroTensor{T,N}, i::Vararg{Integer,N}) where {T,N}
all(1 .≤ i .≤ a.dims) || throw(BoundsError(a, i))
return zero(T)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment