如何在 Julia 中为可变结构设置默认参数?

How can I set default parameters for mutable structs in Julia?

有没有办法在 Julia 中为可变结构添加默认参数?

我正在尝试编写如下内容:

mutable struct Scale
    # Set default values that will be changed by fit!()
    domain_min::Float64 = 0.0
    domain_max::Float64 = 1.0
    range_min::Float64  = 0.0 
    range_max::Float64  = 1.0
end

function fit!(data::Array)
    # Set struct params here using `data`
end

有没有办法做到这一点,或者我应该尝试不同的方法吗?

这正是 Base.@kwdef 所做的:

julia> Base.@kwdef mutable struct Scale
           # Set default values that will be changed by fit!()
           domain_min::Float64 = 0.0
           domain_max::Float64 = 1.0
           range_min::Float64  = 0.0 
           range_max::Float64  = 1.0
       end
Scale

# All parameters to their default values
julia> Scale()
Scale(0.0, 1.0, 0.0, 1.0)

# Specify some parameter(s) using keyword argument(s)
julia> Scale(range_min = 0.5)
Scale(0.0, 1.0, 0.5, 1.0)

我更喜欢使用 Parameters.jl,因为它还提供了一种更好的显示 struct 的方式,这更便于调试:

julia> using Parameters

julia> @with_kw struct A          
       a::Int=5                   
       b::String="hello"          
       c::Float64                 
       end;                                 
                                  
julia> A(c=3.5)                   
A                                 
  a: Int64 5                      
  b: String "hello"               
  c: Float64 3.5                  

或者你也可以走很远的路,用构造函数自己定义它,如果你想以几种可能的方式实例化它,你通常会这样做。

mutable struct Scale                                                                                                                                                                                                                          
    # Set default values that will be changed by fit!()
    domain_min::Float64      
    domain_max::Float64      
    range_min::Float64        
    range_max::Float64       
end

# With default values, but no keywords
julia> Scale(dmin=1.,dmax=2.,rmin=1.,rmax=2.) = Scale(dmin, dmax, rmin, rmax)
Scale

julia> Scale(3.,4.)
Scale(3.0, 4.0, 1.0, 2.0)

# With keyword arguments:
julia> Scale(;dmin=1.,dmax=2.,rmin=1.,rmax=2.) = Scale(dmin, dmax, rmin, rmax)
Scale

julia> Scale(rmax=3., rmin=1.2)
Scale(1.0, 2.0, 1.2, 3.0)

注意两个构造函数之间的区别,一个有分号 ; 另一个没有。我不建议同时使用这两个构造函数,这可能会导致一些混乱。