英文:
what does {a constant number} mean after a variable in julia?
问题
This {M} means这个 {M} 表示 the variable is marked as mutable, indicating it can be modified after its initial assignment.这个变量被标记为可变,表示可以在初始赋值后进行修改。
英文:
what does this {M} mean after the name of a variable?
I have seen something like this in the code:
Struct name{M}
I wanted to know what does this {M} do with our code?
Hi
what does this {M} mean after the name of a variable?
I have seen something like this in the code:
Struct name{M}?
答案1
得分: 2
这允许在编译时而不是运行时传递和操作可用的数字。这可用于动态构建数据结构,稍后Julia可以为其有效地编译代码。
考虑这个结构体:
Base.@kwdef struct AA{M}
a::Array{Int, M} = rand(0:99, fill(3,M)...)
end
字段a
的维度与类型信息一起存储。
这可以这样使用:
julia> AA{1}()
AA{1}([70, 46, 20])
julia> AA{2}()
AA{2}([81 73 38; 65 50 77; 57 87 66])
注意,M
是类型定义的一部分,因此知道M
后,编译器就知道底层字段的类型:
julia> fieldtypes(AA{1})
(Vector{Int64},)
julia> fieldtypes(AA{2})
(Matrix{Int64},)
julia> fieldtypes(AA{3})
(Array{Int64, 3},)
当与宏结合使用时,此行为特别有用(用于在编译时转换代码的程序)。虽然宏显然无法访问变量中的值,但它们可以很好地利用诸如M
之类的数值参数类型。
一个很好的应用示例是https://github.com/JuliaArrays/StaticArrays.jl,当事先知道向量/数组大小时,可以产生更高效的机器代码。
英文:
This allows to pass and manipulate numbers available at compile time rather than runtime. This can be used to dynamically construct data structures where later Julia can efficiently compile code for them.
Consider this struct:
Base.@kwdef struct AA{M}
a::Array{Int, M} = rand(0:99, fill(3,M)...)
end
The dimensionality of the field a
is stored together with the type information.
This could be used as:
julia> AA{1}()
AA{1}([70, 46, 20])
julia> AA{2}()
AA{2}([81 73 38; 65 50 77; 57 87 66])
Note that M
is part of the type definition so knowing M
the compiler knows the types of the underlying fields:
julia> fieldtypes(AA{1})
(Vector{Int64},)
julia> fieldtypes(AA{2})
(Matrix{Int64},)
julia> fieldtypes(AA{3})
(Array{Int64, 3},)
This behavior is particularly useful when combined with macros (programs transforming code at the compile time). While macros obviously cannot access values in the variables, they could make a great use from numeric parameters type such as M
.
A great example of application would be https://github.com/JuliaArrays/StaticArrays.jl when knowing apriori the vector/array size can lead to a far more efficient machine code.
答案2
得分: 1
在Julia中,花括号({}
)用于使用特定的值或类型对变量或类型进行参数化。例如,一个名为x{3}
的变量是使用值3进行参数化的,而Struct name{M}
表示该名字结构体是使用类型M进行参数化的。
英文:
In Julia, curly braces ({}
) are used to parameterize a variable or type with a specific value or type. For example, a variable named x{3}
is parameterized with the value 3, and Struct name{M}
indicates that the name struct is parameterized with the type M.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论