Home > OS >  Loop over @with_kw structure
Loop over @with_kw structure

Time:04-07

I am using Parameters.jl.

Suppose the following MWE:

julia> @with_kw mutable struct test
       a = 5.
       b = .0
       ...... # Plenty of parameters in structure test
       z = .5
       end
test

Suppose now that I would like to have a function that I will call from time to time that would divide all parameters of test except z. I do not know how to do that efficiently, inside a for loop for instance.

The following works but is quite long if I have many parameters!

julia> @with_kw mutable struct test
       a = 5.
       b = .0
       z = .5
       end
julia> t = test()
julia> @unpack a, b = t
julia> a, b = a/2, b/2
julia> @pack! t = a, b

How can I do that with plenty of parameters to be divided by two and not only a and b?

CodePudding user response:

You can do:

julia> setfield!.(Ref(t), 1:3, getfield.(Ref(t), 1:3) ./ 2)
3-element Vector{Float64}:
 2.5
 0.0
 0.25

Notes:

  1. The naming convention recommends naming types with capital letters
  2. Never used untyped containers so this should be
@with_kw mutable struct Test
     a::Float64 = 5.
     b::Float64 = .0
     z::Float64 = .5
end
  1. The number of fields can also be obtained programatically by calling fieldcount(Test)
  • Related