Extend `last` to also work with arrays

It works with strings, but not with arrays, currently this would fail

last([1, 2, 3, 4, 5], 2)

2 Likes

This should work for vectors:

Base.last(v::AbstractVector, n::Integer) = @inbounds v[max(firstindex(v), end-n):end]

But note that this slicing makes a copy

1 Like

+1
It would also be nice to add last(x::AbstractVector, n::Integer). Would you file a PR?

2 Likes

The PR should include first(x::AbstractVector, n::Integer) too.

1 Like
2 Likes

Curious, why is this feature limited to AbstractVector and not any ordered/iterable collection? (as the 1-arg first/last are described for…)

(Also, why is 1-arg first described for iterable collections, and 1-arg last for ordered collections?)

2 Likes

I agree: https://github.com/JuliaLang/julia/pull/34868#issuecomment-594137553

1 Like