Skip to content

Instantly share code, notes, and snippets.

@andyferris
Last active February 25, 2017 10:44
Show Gist options
  • Save andyferris/d7d35b98c654b788828c9c7ac944d307 to your computer and use it in GitHub Desktop.
Save andyferris/d7d35b98c654b788828c9c7ac944d307 to your computer and use it in GitHub Desktop.
Basic recursive static arrays
struct Vec{N,T}
data::NTuple{N,T}
end
@inline function Base.getindex(v::Vec{N}, i::Int) where {N}
@boundscheck if i < 1 || i > N
throw(BoundsError(v,i))
end
@inbounds return v.data[i]
end
@inline function Base.map{N,T}(f, m::Vec{N,T})
T2 = Base.promote_op(f, T)
@inbounds return Vec{N,T2}(map_1d(f, v.data))
end
struct Mat{N,M,T}
data::NTuple{N,NTuple{M,T}}
end
@inline function Base.getindex(m::Mat{N,M}, i::Int, j::Int) where {N,M}
@boundscheck if i < 1 || i > N || j < 1 || j > N
throw(BoundsError(m,(i,j)))
end
@inbounds return m.data[i][j]
end
@inline function Base.map{N,M,T}(f, m::Mat{N,M,T})
T2 = Base.promote_op(f, T)
@inbounds return Mat{N,M,T2}(map_2d(f, m.data))
end
Base.@propagate_inbounds map_2d(f, m::Tuple) = _map_2d((), f, m)
Base.@propagate_inbounds _map_2d(t::Tuple, f, ::Tuple{}) = t
Base.@propagate_inbounds _map_2d(t::Tuple, f, m::Tuple) = _map_2d((t..., map_1d(f, t[1])), f, Base.tail(m))
Base.@propagate_inbounds map_1d(f, v::Tuple) = _map_1d((), f, v)
Base.@propagate_inbounds _map_1d(t::Tuple, f, ::Tuple{}) = t
Base.@propagate_inbounds _map_1d(t::Tuple, f, v::Tuple) = _map_1d((t..., f(v[1])), f, Base.tail(v))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment