Open
Description
When calling Base.last(::Tuple,::Int)
, the result is of type Vector, but when you manually index into the tuple, the result is a tuple. Is this an intentional design choice? It seems counter-intuitive. The same applies to Base.first
.
- The output of
versioninfo()
:
Julia Version 1.10.4
Commit 48d4fd48430 (2024-06-04 10:41 UTC)
Build Info:
Official https://julialang.org/ release
Platform Info:
OS: macOS (arm64-apple-darwin22.4.0)
CPU: 8 × Apple M2
WORD_SIZE: 64
LIBM: libopenlibm
LLVM: libLLVM-15.0.7 (ORCJIT, apple-m1)
Threads: 4 default, 0 interactive, 2 GC (on 4 virtual cores)
Environment:
JULIA_EDITOR = vim
- I installed Julia using the Homebrew command
brew install julia
. - MWE:
t = (1,2,3,4); @show Base.last(t,2); @show t[end-1:end]; println(); @show Base.first(t,2); @show t[1:2];
with output
Base.last(t, 2) = [3, 4]
t[end - 1:end] = (3, 4)
Base.first(t, 2) = [1, 2]
t[1:2] = (1, 2)
A simple way to fix it would be to define the following functions.
function Base.last(t::Tuple,n::Integer)
n < 0 && throw(ArgumentError("Number of elements must be nonnegative"))
@inbounds t[range(stop=lastindex(t), length=min(n, Base.checked_length(t)))]
end
function Base.first(t::Tuple,n::Integer)
n < 0 && throw(ArgumentError("Number of elements must be nonnegative"))
@inbounds t[range(begin, length=min(n, Base.checked_length(t)))]
end