Thursday, 14 April 2016

Julia: Parametric Types: generic programming


Just like you are giving type to parameters of a method, you can also specify a type for composite types.

julia> type Dimension{T}
           x::T
           y::T
           z::T
           title::AbstractString
       end

julia> dim1 = Dimension{Int64}(1, 2, 3, "Location1")
Dimension{Int64}(1,2,3,"Location1")

julia> dim2 = Dimension{Float64}(12.34, 45.56, 56.78, "Location2")
Dimension{Float64}(12.34,45.56,56.78,"Location2")

julia> dim3 = Dimension{Bool}(true, true, false, "Location3")
Dimension{Bool}(true,true,false,"Location3")


Dimension{Int64} : replace parametric type T with Int64
Dimension{Float64} : replace parametric type T with Float64
Dimension{Bool} : replace parametric type T with Bool

By using parametric types, you can declare unlimited number of types like  Dimension{Int64}, Dimension{Float64}, Dimension{Bool}, Dimension{Int32} etc.,


Dimension is also a valid type, all parametric types of Dimension are subtypes of Dimension.

julia> Dimension{Int64} <: Dimension
true

julia> Dimension{Int32} <: Dimension
true

julia> Dimension{UInt32} <: Dimension
true

julia> Dimension{Float64} <: Dimension
true

julia> Dimension{Bool} <: Dimension
true


Passing Parametric types to methods

julia> function processDIm(dim::Dimension{Int64})
           dim.x^2+dim.y^2+dim.z^2
       end
processDIm (generic function with 1 method)

julia> dim1 = Dimension{Int64}(2, 3, 5, "Location X")
Dimension{Int64}(2,3,5,"Location X")

julia> processDIm(dim1)
38


Following is the better way to represent generic method.

julia> function processDIm{T<:Real}(dim::Dimension{T})
           dim.x^2+dim.y^2+dim.z^2
       end
processDIm (generic function with 2 methods)

julia> processDIm(Dimension{Float64}(2.34, 3.45, 5.67, "Location X"))
49.527


Adding more than one parametric type
You can add more than one parametric type for a composite type.

julia> type Employee{T, U}
           firstName::T
           id::U
       end

julia> emp1=Employee{AbstractString, AbstractString}("Krishna", "E532134")
Employee{AbstractString,AbstractString}("Krishna","E532134")

julia> emp1=Employee{AbstractString, Int64}("Krishna", 123)
Employee{AbstractString,Int64}("Krishna",123)






Previous                                                 Next                                                 Home

No comments:

Post a Comment