On Thursday, April 23, 2015 at 2:36:45 PM UTC-5, Kuba Roth wrote:
>
> This is my first  time writing macros in Julia. I've read related docs but 
> could not find an example which works with the arbitrary number of 
> arguments. 
> So in my example below the args... works correctly with string literals 
> but for the passed variables it returns their names and not the values.


Here's the result of the last thing you called (note that I don't even have 
testB and testC defined!)

julia> macroexpand(:(@echo testB testC))
:(for #6#x = (:testB,:testC) # line 3:
        print(#6#x," ")
    end)

What ends up in `args` is the argument tuple to the macro. Typically, you 
wouldn't process that in the final output--otherwise you could just use a 
function! Instead, you'd splice each argument individually (`$(args[1])`, 
`$(args[2])`, etc.) using a loop in the macro body, with each element of 
the loop emitting more code, then gluing the pieces together at the end.

Style notes: Typically, no space between function/macro name and formal 
arguments list. Multiline expressions are easier to read in `quote`/`end` 
blocks.

Anyways, here's one way to do sort of what you want in a way that requires 
a macro (though I still wouldn't use one for this! Didactic purposes only!):

macro unrolled_echo(args...)
    newxpr = Expr(:block) # empty block to hold multiple statements
    append!(newxpr.args, [:(print($arg, " ")) for arg in args]) # the 
arguments to the :block node are a list of Exprs
    newxpr # return the constructed expression
end

Reply via email to