“在Julia中,变量后面的{一个常数}是什么意思?”

huangapple go评论66阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月7日 21:24:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194195.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定