Last active
November 17, 2017 08:58
-
-
Save v-i-s-h/9efd1e227908aaa1595a644d4e46e3d2 to your computer and use it in GitHub Desktop.
Julia: Making derived type objects with parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract type baseType end | |
function call( ::Type{T}, params... ) where T <: baseType | |
return T( params... ) | |
end | |
# call (generic function with 1 method) | |
type derived1 <: baseType | |
x::Int64 | |
y::Float64 | |
function derived1( x::Int64, y::Float64 ) | |
new( x, y ) | |
end | |
end | |
type derived2 <: baseType | |
x::Int64 | |
y::Float64 | |
z::Float64 | |
function derived2( x::Int64, y::Float64, z::Float64 ) | |
new( x, y, z ) | |
end | |
end | |
x1 = derived1( 2, 3.0 ) | |
x2 = derived2( 3, 3.0, 4.0 ) | |
# derived2(3, 3.0, 4.0) | |
function factory( ::Type{T}, params... ) where T <: baseType | |
return call( T, 2, params... ) | |
end | |
# factory (generic function with 1 method) | |
factory( derived1, 2.0 ) | |
# derived1(2, 2.0) | |
factory( derived2, 1.0, 2.2 ) | |
# derived2(2, 1.0, 2.2) | |
z = Vector{baseType}() | |
push!( z, derived1(2,12.0) ) | |
# 1-element Array{baseType,1}: | |
# derived1(2, 12.0) | |
x = Dict( derived1 => (2.0), derived2 => (3.0,4.0) ) | |
# Dict{DataType,Any} with 2 entries: | |
# derived1 => 2.0 | |
# derived2 => (3.0, 4.0) | |
for (k,v) in x | |
push!( z, factory(k,v...) ) | |
end | |
z | |
# 3-element Array{baseType,1}: | |
# derived1(2, 12.0) | |
# derived1(2, 2.0) | |
# derived2(2, 3.0, 4.0) | |
w = Vector{baseType}() | |
for (k,v) in x | |
# push!( w, call( k, 2, v... ) ) | |
push!( w, k( 2, v... ) ) | |
end | |
# 2-element Array{baseType,1}: | |
# derived1(2, 2.0) | |
# derived2(2, 3.0, 4.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment