Function generation interpolating symbol with a string

Hi all,

not sure the title is clear enough, but I was struggling to find a clear description. Although I think what I am trying to do is pretty straight forward and the problem is that I simply don’t understand how macros work.

Situation it’s as follows: I have a lot of boilerplate code to load a dictionary that then gets transformed into a struct. Currently, I have to write a function that checks if the key is present, and then performs some operations.

function set_continue_to(data::OrderedDict)
    if haskey(data, :continue_to)
      # do Stuff

Could I do something like this?

@set continue_to begin
# do Stuff


I guess here the problem would be that when defining the macro, data won’t be available. Also, I don’t know how to generate the function name set_$property with the macro.

Any guidance/simpler approaches would be appreciated.

This sounds like a poster child for using higher-order functions, not code generation:

function set_property(dostuff::Function, data::OrderedDict, property::Symbol)
    if haskey(data, property)

do set_property(data, :continue_to) property
    ... do stuff with the property ...

or some variation thereof (depending on what kind of operations you want to perform).


I am currently watching your talk (thanks a lot!), and it seems very obvious in retrospect that a higher-order function is the solution, but I really wanted to tinker with macros. I am feeling a bit ashamed, even. Specially after seeing this on the talk:

My guess: roughly 2/3 of the Julia macro questions are from people who shouldn’t be using macros.

What can I say? You got me :stuck_out_tongue:

1 Like