Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining print()-like functions for a new type in Julia

Tags:

printing

julia

In order to make a new type printable in Julia, which methods should one define? I believe that one should only define show, which will then induce the behavior of other functions like:

  • print
  • string
  • repl_show
  • showcompact
  • showall

Which of these methods need to be defined for a new type?

like image 310
John Myles White Avatar asked Jan 01 '13 23:01

John Myles White


1 Answers

If the Base source is any reliable reference, base/version.jl has only print() and show defined (and show depends on print)

function print(io::IO, v::VersionNumber)
    print(io, v.major)
    print(io, '.')
    print(io, v.minor)
    print(io, '.')
    print(io, v.patch)
    if !isempty(v.prerelease)
        print(io, '-')
        print_joined(io, v.prerelease,'.')
    end
    if !isempty(v.build)
       print(io, '+')
       print_joined(io, v.build,'.')
    end
end
show(io, v::VersionNumber) = print(io, "v\"", v, "\"")

It seems at this point it is up to you if you want to rely on one common function; you just implement all such functions that way. Example:

type Foo
end
import Base.string
function string(x::Foo)
    return "a Foo()"
end
import Base.print
print(io::IO, x::Foo) = print(io, string(x))
import Base.show
show(io::IO, x::Foo) = print(io, "This is ", x)

-

julia> f = Foo()
This is a Foo()
like image 132
lgautier Avatar answered Oct 11 '22 23:10

lgautier