Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get simple name of type in Julia?

Say I have

struct MyStruct{T,U}
  a::T
  b::U
end

I'd like to define a custom show which eliminates a lot of noise from the full type.

E.g. if I create the following:

z = MyStruct((a=1,b=2),rand(5))

then typeof shows much more than I want:

julia> typeof(z)
MyStruct{NamedTuple{(:a, :b), Tuple{Int64, Int64}}, Vector{Float64}}

How can I programmatically get just MyStruct from z into a string?

like image 975
Alec Avatar asked Nov 20 '21 04:11

Alec


People also ask

What is a type Julia?

Julia's type system is designed to be powerful and expressive, yet clear, intuitive and unobtrusive. Many Julia programmers may never feel the need to write code that explicitly uses types. Some kinds of programming, however, become clearer, simpler, faster and more robust with declared types.

What is struct in Julia?

Structures (previously known in Julia as "Types") are, for the most (see later for the difference), what in other languages are called classes, or "structured data": they define the kind of information that is embedded in the structure, that is a set of fields (aka "properties" in other languages), and then individual ...

What is abstract type in Julia?

Abstract types allow the construction of a hierarchy of types, providing a context into which concrete types can fit. This allows you, for example, to easily program to any type that is an integer, without restricting an algorithm to a specific type of integer.


1 Answers

Some lengthy discussions on Discourse here and here, which provide at least these two solutions (the second one generalising the first):

julia> Base.typename(typeof(z)).wrapper
MyStruct

julia> name(::Type{T}) where {T} = (isempty(T.parameters) ? T : T.name.wrapper)
name (generic function with 1 method)

julia> name(typeof(z))
MyStruct
like image 58
Nils Gudat Avatar answered Nov 15 '22 09:11

Nils Gudat