Hi,
Is it possible to define a function, structure, macro or whatever to get sth like this:
julia> a = somefunc()
“a”
where the string contains the variable name ? I would like a way to print the variable name without writing it twice (once for the declaration and once for the string).
no, the right hand side of = can’t see what’s left to it. Because the right-hand side has to be “evaluated” first, and the return value is bonded to left-hand side (variable name)
Also, see the VSCode Workspace for that same information.
However, that is only going to work for global variables which should generally be avoided (unless they are const). I suggest instead you put all your parameters into a NamedTuple (or a Dictionary if you don’t know all of the parameters ahead of time) and work with that instead.
julia> parameters = (a=1, b="hello")
(a = 1, b = "hello")
julia> keys(parameters)
(:a, :b)
julia> string.(keys(parameters))
("a", "b")
Named Tuples are faster to use than Dictionaries but the names will be stored as Symbol rather than String. Dictionaries can use strings directly as keys and you can add to them after creation.
julia> params = Dict("c" => 8.8)
Dict{String, Float64} with 1 entry:
"c" => 8.8
julia> params["d"] = 10
10
julia> params
Dict{String, Float64} with 2 entries:
"c" => 8.8
"d" => 10.0
julia> keys(params)
KeySet for a Dict{String, Float64} with 2 entries. Keys:
"c"
"d"
Nested collections may also help avoid such long variable names. Accessing the variables directly with dot syntax isn’t any shorter (e.g. parameters.files.schedule), but collections can make it easier to pass only relevant variables to functions.
julia> function list_employees(employees)
for name in values(employees)
println(name)
end
end
list_employees (generic function with 1 method)
julia> parameters = (
files = (
schedule = "Documents/schedule.xlsx",
output = "Documents/out.txt",
),
employees = (
CEO = "John",
manager = "Barb",
cashier = "Fred",
),
minimum_wage = 7.50,
)
(files = (schedule = "Documents/schedule.xlsx", output = "Documents/out.txt"), employees = (CEO = "John", manager = "Barb", cashier = "Fred"), minimum_wage = 7.5)
julia> list_employees(parameters.employees)
John
Barb
Fred
It is also common to rename a variable to something shorter at the top of a function where the context is more clear and then do the real work with those shorter names.
function update_schedule(parameters)
schedule = parameters.files.schedule
cashier = parameters.employees.cashier
# do stuff
end