John Myles White
John Myles White

Reputation: 2929

Defining print()-like functions for a new type in 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:

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

Upvotes: 9

Views: 1519

Answers (1)

lgautier
lgautier

Reputation: 11555

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()

Upvotes: 10

Related Questions