Skip to content

Base.last(::Tuple,::Integer) and Base.first(::Tuple,::Integer) return Vectors #55427

Open
@jecs

Description

@jecs

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.

  1. 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
  1. I installed Julia using the Homebrew command brew install julia.
  2. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    collectionsData structures holding multiple items, e.g. setsfeatureIndicates new feature / enhancement requests

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions