Hi,
macro Name(arg)
string(arg)
end
Household = @with_kw (r=0.03,
β=0.97)
Model = Household()
function doplot(Model, x)
@unpack r = Model
plot(x, ylabel=@Name(x), title="r=$r")
end
draw = rand(100)
doplot(Model, draw)
What should I do to obtain “draw” in the y axis label, instead of “x”?
Thank you.
Your problem is that, since doplot
is a function, only the value of draw
is passed to it. doplot
never has any chance to see the name of the draw
variable in the outer context.
So the macro call needs to happen in the outer context; inside doplot
is too late. You could perhaps transform the whole doplot
function into a macro, but I would advise against it since:
- it is good practice to restrict the use of macros to a bare minimum and have the real work be performed by a regular function
- you have a macro call (
@unpack
) inside doplot
, and calling macros inside macros can be tricky.
Instead, I would do something along the lines of (the example below has been modified to avoid calling plot
and waiting for long compilation times when testing):
using Parameters
Household = @with_kw (r=0.03,
β=0.97)
macro name(x)
quote
($(esc(x)), $(string(x)))
end
end
function doplot(m, (x, label))
@unpack r = m
# plot(x, ylabel=label, title="r=$r")
@show r
@show x
@show label
nothing
end
julia> let
model = Household()
draw = rand(10)
doplot(model, @name draw)
end
r = 0.03
x = [0.100556, 0.312134, 0.641569, 0.38493, 0.817918, 0.818177, 0.139622, 0.0419971, 0.408327, 0.889146]
label = "draw"
3 Likes