Individual mapping of composite types in Julia

Suppose you define a new composite type in Julia and a variable of this type:

type MyType α::Int64 β::Vector{Float64} γ::Float64 MyType(α::Int64, β::Vector{Float64}, γ::Float64) = new(α, β, γ) end mt = MyType(5, [1.2, 4.1, 2], 0.2) 

Now, if you are in REPL mode, you can simply check the mt value by typing mt and pressing Enter:

 mt MyType(5,[1.2,4.1,2.0],0.2) 

If I want to customize how MyType variables are MyType , I can define a function and use it as customized_display(mt) :

 function customized_display(me::MyType) println("MyType") println("α:$(me.α), β:$(me.β), γ:$(me.γ)") end customized_display(mt) MyType α:5, β:[1.2,4.1,2.0], γ:0.2 

But using another function to display the mt values ​​seems redundant. What function do I need to expand so that just by typing mt , the customized display will be displayed?

+7
read-eval-print-loop julia-lang
source share
2 answers

You must define one of the following (they will work and have the same effect):

 function Base.show(io::IO, me::MyType) println(io, "MyType") println(io, "α:$(me.α), β:$(me.β), γ:$(me.γ)") end function Base.writemime(io::IO, ::MIME"text/plain", me::MyType) println(io, "MyType") println(io, "α:$(me.α), β:$(me.β), γ:$(me.γ)") end 
+5
source share

Note : spencerlyon2's answer is no longer correct, as from Julia 0.5 and later.

Given your type

 type MyType α::Int64 β::Vector{Float64} γ::Float64 end 

If you want to configure a single-line display, add the Base.show method as follows:

 function Base.show(io::IO, me::MyType) print(io, "MyType: α:", me.α, " β:", me.β, " γ:", me.γ) end 

An example of using a single line display:

 julia> [MyType(5, [1.2, 4.1, 2], 0.2)] 1-element Array{MyType,1}: MyType: α:5 β:[1.2, 4.1, 2.0] γ:0.2 

By convention, this method should not include any newlines. This is so that it displays well when embedded in other objects, such as arrays or matrices. As a rule, he prefers to output something that can be analyzed and evaluated into an object equal to the one shown, but this is not a strict rule.

If you want to configure a multi-line display, add the Base.show method as follows:

 function Base.show(io::IO, ::MIME"text/plain", me::MyType) println(io, "MyType") print(io, "α:", me.α, " β:", me.β, " γ:", me.γ) end 

Please note that if you do not enable this method, a single line display will be used. A multi-line display is used in REPL when your object is displayed on its own:

 julia> MyType(5, [1.2, 4.1, 2], 0.2) MyType α:5 β:[1.2, 4.1, 2.0] γ:0.2 

By convention, a multi-line display should not print any trailing newlines.

+6
source share

All Articles