What is empty index notation?

I saw the following notation in the documentation of Makie.

x[] = 3.34

https://makie.juliaplots.org/stable/documentation/nodes/index.html#the_observable_structure

What is this syntax?

1 Like

You set the only element in x to 3.34

In this case it is:

julia> x = Observable(0.0)
Observable{Float64} with 0 listeners. Value:
0.0

julia> dump(x)
Observable{Float64}
  listeners: Array{Any}((0,))
  val: Float64 0.0
  inputs: #undef

julia> @which x[]
getindex(observable::Observable) in Observables at C:\Users\Oli\.julia\packages\Observables\OFj0u\src\Observables.jl:306

julia> @less x[]
Base.getindex(observable::Observable) = observable.val

It is setting the val part of the Observable type.
Operator [] is called derefencing a Ref (reference) which you can find in the docs:
https://docs.julialang.org/en/v1.7/base/c/#Core.Ref
It is just a similar definition in Base:

julia> y=Ref(5)
Base.RefValue{Int64}(5)

julia> dump(y)
Base.RefValue{Int64}
  x: Int64 5

julia> @less y[]
getindex(b::RefValue) = b.x
2 Likes

You can also use this syntax for accessing the value of a zero-dimensional array. I would guess that this is where the syntax originated, N indices for N dimensions.

1 Like

How can this be explained?

julia> x = [:a]
1-element Vector{Symbol}:
 :a

julia> x[]
:a

The a[] syntax will return the only element in a.

julia> x = [:a]
1-element Vector{Symbol}:
 :a

julia> x[]
:a

julia> x = reshape([:a], Val(0))
0-dimensional Array{Symbol, 0}:
:a

julia> x[]
:a

julia> x = reshape([:a], Val(2))
1×1 Matrix{Symbol}:
 :a

julia> x[]
:a

This doesn’t work if a doesn’t have exactly one element

julia> x = [:a, :b]
2-element Vector{Symbol}:
 :a
 :b

julia> x[]
ERROR: BoundsError: attempt to access 2-element Vector{Symbol} at index []

julia> x = []
Any[]

julia> x[]
ERROR: BoundsError: attempt to access 0-element Vector{Any} at index []
1 Like

I mean why does it do that? It is inconsistent with @DNF’s guess

Does Matlab do the same thing?

It does that because indices may be omitted if all the trailing dimensions are of length 1. This implies that, for a 1-element Array, x[] is equivalent to x[1], irrespective of how many dimensions the array has.

I am uncertain if Matlab does the same.

5 Likes

The way I think about it is as follows x[] is the same as getindex(x). So if there is one-argument getindex defined for type of value x then x[] will work.

2 Likes