DboyLiao
DboyLiao

Reputation: 483

Function with no arguments but with type in Julia

I recently go through some source codes of Julia and find some functions seem mysterious to me.

There is some function defined in Julia source code where they have no arguments but do have type annotations.

For example: line 20 in abstractarray.jl

I try the ndims function a bit,

it seems like ndims can take the type itself as argument and return the correct value:

julia> ndims(AbstractArray{Float64, 2})
       2
julia> ndims([1.1 0.3; 0. 0.5])
       2

Can someone explain to me how (::DataType) works in methods? Or what does it mean in Julia?

Upvotes: 4

Views: 996

Answers (1)

Isaiah Norton
Isaiah Norton

Reputation: 4366

When exploring the behavior of a function in Julia, it is important to understand which specific method is being called. Julia is organized around multiple dispatch, so a single name such as ndims may be associated with different implementations -- chosen by the type of the arguments. To see how ndims is implemented, we can use the @which macro to determine the implementation chosen for a specific invocation:

julia> @which ndims(AbstractArray{Float64, 2})
ndims{T,n}(::Type{AbstractArray{T,n}}) at abstractarray.jl:61

julia> @which ndims([1.1 0.3; 0. 0.5])
ndims{T,n}(::AbstractArray{T,n}) at abstractarray.jl:60

The current implementations in abstractarray.jl are as follows:

ndims{T,n}(::AbstractArray{T,n}) = n
ndims{T,n}(::Type{AbstractArray{T,n}}) = n

Both signatures are parametric methods taking the parameters {T,n}.

  • The first signature is for an instance with the type AbstractArray{T,n} -- such as, in your example, [1.1 0.3; 0. 0.5] (below several layers of abstraction).
  • The second signature is for the type AbstractArray{T,n} itself.

(neither signature names the argument, although they obviously both do accept an argument. because the behavior depends only on the type signature of the argument, a name is not required)

The underlying ideas are explained in the types and methods sections of the Julia manual.

Upvotes: 14

Related Questions