Skip to content

Instantly share code, notes, and snippets.

@tuzzeg
Created May 9, 2014 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuzzeg/3f4ada314d0dbccde5d7 to your computer and use it in GitHub Desktop.
Save tuzzeg/3f4ada314d0dbccde5d7 to your computer and use it in GitHub Desktop.
Julia types
# Define holder for Int, parametrized with number.
type I{N}
x::Int
end
# We have access to type parameter in runtime.
show{N}(x::I{N}) = "N(x=$(x.x) N=$N)"
# We can specialize implementation by type parameter.
show(x::I{1}) = "1(x=$(x.x))"
println(show(I{3}(1)))
#> N(x=1 N=3)
println(show(I{1}(1)))
#> 1(x=1)
# Define type parametrized by type
type H{T}
v::T
end
show{T}(x::H{T}) = "generic($x)"
# We can have function specialized for concrete type
show(x::H{Int}) = "Int($x)"
# We can have function specialized for all subtypes of String
show{T<:String}(x::H{T}) = "String($x)"
# And even specialization for the specific subtype
# (note that ASCIIString <: String)
show(x::H{ASCIIString}) = "ASCIIScting($x)"
println(show(H(1)))
#> Int(H{Int64}(1))
println(show(H("a")))
#> ASCIIScting(H{ASCIIString}("a"))
println(show(H{String}("a")))
#> String(H{String}("a"))
type D{K,V}
k::K
v::V
end
show{K,V}(kv::D{K,V}) = "{K=$K V=$V}($kv)"
println(show(D(1, "a")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment