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?
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}
.
AbstractArray{T,n}
-- such as, in your example, [1.1 0.3; 0. 0.5]
(below several layers of abstraction).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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With