How to build a tuple of kwargs to pass to a function in a macro?

377 views
Skip to first unread message

Glen Hertz

unread,
Nov 10, 2013, 12:28:45 PM11/10/13
to julia...@googlegroups.com
Hi,

I have a function that takes keyword arguments that I want to call with a macro.  I've seen the :kw in expressions but I want to construct a collection of tuples to pass to the kwargs function so I can use this collection of tuples elsewhere.  What I can't figure out is how to insert a Symbol into the macro so that it is treated as a Symbol and doesn't get evaluated as a Symbol.  How do you escape a symbol in a macro?  Also, how do you generate a tuple on the fly that you don't know the size of ahead of time?

In my returned code, I want:

((:a, 3), (:b, 1))

I have something like this (as a silly test):

function kwargsfunc(args...; kwargs...)
    @show args
    @show kwargs
end
macro tokwargs(expr)
    code = :(Any[])  # using array since can't push! onto tuple
    dump(expr,10)
    for sym in expr.args  # an array of symbols
       push!(code.args, (symbol(string(sym)), sym))  # escaping "name" symbol doesn't work this way
    end
    # need to somehow convert array of tuples to an tuple of tuples...
    return esc(code)
end
a = 3
b = 1
t = @tokwargs([a,b])
dump(t)
kwargsfunc(t) # test
kwargsfunc(;t...)  # this is what I want to do


Thanks for any help.

Glen

Jameson Nash

unread,
Nov 10, 2013, 12:49:47 PM11/10/13
to julia...@googlegroups.com
To answer you questions:

(a) Meta.quot(:symbol) will insert a literal symbol. You can do this
manually by writing `Expr(:quot, :symbol)` if you prefer -- the result
is the same.

(b) Expr(:tuple, args...) is the expression form of a tuple.
tuple(args...) is the equivalent runtime expression.

(c) Code example:
function kwargsfunc(args...; kwargs...)
@show args
@show kwargs
end
macro tokwargs(expr)
code = Expr(:tuple)
for sym in expr.args # an array of symbols
push!(code.args, Expr(:tuple,
Meta.quot(symbol(string(sym))), sym))
end
return esc(code)
end
a = 3
b = 1
t = @tokwargs([a,b])
dump(t)
kwargsfunc(t) # test
kwargsfunc(;t...) # this is what I want to do

Reply all
Reply to author
Forward
0 new messages