Seanny123
Seanny123

Reputation: 9346

Why does Julia Int64, Float64 and boolean support getindex

In Julia, you can declare an Int64, Bool or a Float64 and index it with 1.

julia>  aa = 10
10

julia> typeof(10)
Int64

julia> aa[1]
10

julia> aa[0]
ERROR: BoundsError
Stacktrace:
 [1] getindex(::Int64, ::Int64) at .\number.jl:78
 [2] top-level scope at none:0

julia> aa[2]
ERROR: BoundsError
Stacktrace:
 [1] getindex(::Int64, ::Int64) at .\number.jl:78
 [2] top-level scope at none:0

Are there practical or theoretical reasons for this functionality to exist? I have never seen it in any other language I've used (Python, Ruby, Matlab, C++).

Upvotes: 4

Views: 262

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69879

The reason is twofold:

  1. Numbers are treated by Julia as 0-dimensional containers.
  2. If you add 1 as a dimension index number in getindex then it is not an error, even if 1 is beyond the dimensionality of the container.

These two rules in combination lead to the behavior you describe. Here are some more examples of the same:

julia> a = 1
1

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

julia> a[]
1

julia> a[1,1,1,1]
1

julia> b[2,1,1,1,1]
2

and note that standard functions defined for containers are defined for numbers and behave as for 0-dimensional objects, e.g.:

julia> size(a)
()

julia> axes(a)
()

There is an open PR that gives more details how omitted and extra indices work.

Upvotes: 5

Related Questions