'Loop over @with_kw structure
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?
Solution 1:[1]
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:
- The naming convention recommends naming types with capital letters
- Never used untyped containers so this should be
@with_kw mutable struct Test
a::Float64 = 5.
b::Float64 = .0
z::Float64 = .5
end
- The number of fields can also be obtained programatically by calling
fieldcount(Test)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Przemyslaw Szufel |
