Why doesn't first(Array, Int64) work?

Why don’t these do the same thing?

julia> [1,2,3][1:2]
2-element Array{Int64,1}:
 1
 2

julia> first([1,2,3], 2)
ERROR: MethodError: no method matching first(::Array{Int64,1}, ::Int64)
Closest candidates are:
  first(::AbstractArray) at abstractarray.jl:270
  first(::AbstractString, ::Integer) at strings/basic.jl:606
  first(::Any) at abstractarray.jl:288
Stacktrace:
 [1] top-level scope at none:0

Because there is no such function. Maybe you want Iterators.take.

1 Like

I was surprised to find that function didn’t exist because

julia> first([1,2,3])
1

does exist. I’m curious if there is a reason why it shouldn’t exist?

See my reply to your other, related question, you can do:

julia> getindex([1,2,3], 1:2)
2-element Array{Int64,1}:
 1
 2

This is actually defined on master, so it will be in the upcoming Julia 1.6. See https://github.com/JuliaLang/julia/pull/34868 for reference.

3 Likes

This would only work for arrays with one-based indexing, and anyway has no advantage over [1,2,3][1,2]. I believe the point of first is exactly to work generically for all indexing types and iterables.

1 Like

Agreed - I guess I fused this question with another of OP’s question that he asked around the same time, which is why you can’t do [[1,2,3], [2,3,4]].[1:2] - that’s where getindex comes in handy.

1 Like