I have a weird setfields use case:
p = Normal(1,2);
setproperties(p, μ=0.5)
works but I would like to do
a=:μ;
setproperties(p, a=0.5)
such that I can pass a
to a function…how do I do that?
I have a weird setfields use case:
p = Normal(1,2);
setproperties(p, μ=0.5)
works but I would like to do
a=:μ;
setproperties(p, a=0.5)
such that I can pass a
to a function…how do I do that?
You can use Pair
syntax for this
julia> function foo(;a =1)
return a
end
foo (generic function with 1 method)
julia> x = :a
:a
julia> foo(; x => 5)
5
Are you sure that can be used with setfields for changing a struct?
Edit: See answer above.
Does it work? If it’s a keyword argument it should work. Though I dont know what package setproperties
is from so its hard to help
No, I don’t get it to work. Setproperties
is from the package Setfield
julia> using Distributions, Setfield, NamedTupleTools
julia> p = Normal(1, 2)
Normal{Float64}(μ=1.0, σ=2.0)
julia> x = :μ;
julia> setproperties(p, namedtuple((x,), (0.5,)))
Normal{Float64}(μ=0.5, σ=2.0)
These are already great answers. As @hendri54 noted, you can also pass NamedTuples
to setproperties
:
julia> using ConstructionBase # or using Setfield, if you like
julia> dist = (μ=10, σ=20, α=30);
julia> patch = (μ=1, α=2);
julia> setproperties(dist, patch)
(μ = 1, σ = 20, α = 2
julia> a = :μ; patch = (;a => 100,)
(μ = 100,)
julia> setproperties(dist, patch)
(μ = 100, σ = 20, α = 30)