`end` and `:` as an argument

Is there a way to pass end as an argument? For example, when we have a tuple of vectors, we can construct a tuple of the first entries of the vectors as

julia> t = (rand(2), rand(3), rand(4))
([0.38328, 0.764218], [0.821559, 0.252655, 0.571611], [0.572755, 0.512441, 0.389949, 0.875044])

julia> getindex.(t,1)
(0.38328016631616735, 0.8215592160037497, 0.5727552055080367)

I would like to use end instead of 1 here to construct a tuple of the last entries of the vectors.

Related, to get the first two entries of the vectors, we can do

julia> getindex(t, 1:2)
([0.38328, 0.764218], [0.821559, 0.252655, 0.571611])

I wonder if there is a way to pass : instead of 1:2 to get all the entries of the vectors.

I’m aware that there are many different ways to achieve the aforementioned goals. For example, I can do

julia> (v->v[end]).(t)
(0.7642183236367728, 0.5716110528720979, 0.8750440080310231)

julia> (v->v[:]).(t)
([0.38328, 0.764218], [0.821559, 0.252655, 0.571611], [0.572755, 0.512441, 0.389949, 0.875044])

but I’m just curious if things similar to getindex.(t,end) and getindex.(t, :) are possible.

getindex.(t,endof.(t)) should do what you want. (x[end] is just syntactic sugar for x[endof(x)].)

4 Likes