mohamedmoussa
mohamedmoussa

Reputation: 559

Julia macro expansion inside function

I have a macro that looks like this

macro multishift(L...)
    ex = :(0)
    for d in L
        ex =  :($ex | 1 << Int32($d))
    end
    return ex
end

So @multishift(1,2) will expand out to 0 | 1 << Int32(1) | 1 << Int32(2). Now I add a function like so, and call it:

f(L...) = @multishift(L...)
println(f(1,2))

This won't work. I'll get an error that L is not defined. I can see what is happening here - the macro is being expanded out with L instead of the tuple (1,2).

What is the correct way to get around this?

Upvotes: 0

Views: 458

Answers (1)

phipsgabler
phipsgabler

Reputation: 20950

You could interpolate into @eval:

julia> f(L...) = @eval @multishift($(L...))
f (generic function with 1 method)

julia> f(1,2)
6

julia> a, b, c = 1, 2, 3
(1, 2, 3)

julia> f(a, b, c)
14

But that doesn't feel right. You lose all powers of it being a macro: instead of expanding once at compile time, it expands every time it's called. With the given function, you should test whether there's much gained at all by using a macro.

Upvotes: 1

Related Questions