I apologize that this question may not generalize to many other people’s problems but I’m having a lot of trouble coming up with a macro. Say for example, I have this dictionary
dict = Dict("a" => 1, "b" => Dict("inner" => "test"))
I want to create a macro getField(fields...)
that generates a function for me depending on the number of arguments passed. For example, if one argument @getField "a"
is passed it returns the function
x::Dict{String, Any} -> begin
if !("a" in keys(x))
return ""
end
return x["a"]
end
And if two arguments are passed @getField "b" "inner"
then it returns the function
x::Dict{String, Any} -> begin
if !("b" in keys(x))
return ""
end
if !("inner" in keys(x["b"]))
return ""
end
return x["b"]["inner"]
end
Basically, go through each layer of the dictionary and make sure the field is there and if it not there, return an empty string. My code so far that fails horribly is
macro getField(fields...)
quote
x::Dict{String, Any} -> begin
if !($(fields[1]) in keys(x))
return ""
end
tmp = $(fields[1])
if $(length(fields)) > 1
for f in $(fields[2:end])
if !(f in tmp)
return ""
end
tmp = tmp[f]
end
end
end
end
end
Can someone help me understand how to loop over the fields passed to create the function?