Last active
February 25, 2017 10:44
-
-
Save andyferris/d7d35b98c654b788828c9c7ac944d307 to your computer and use it in GitHub Desktop.
Basic recursive static arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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