Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 661
DboyLiao Avatar asked Dec 10 '22 23:12

DboyLiao


1 Answers

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.

like image 142
Isaiah Norton Avatar answered Dec 13 '22 13:12

Isaiah Norton