How to assign value in macro from a function call

I tried to follow this example to build a macro that does such thing: x = f(args...):

julia> function mysum(args...)
             sum([x for x in args])
             end
mysum (generic function with 1 method)

julia> macro myassign(sym, f, args...)
           @show sym
           @show f
           @show args

           return esc(Expr(:(=), esc(sym), :($f($(esc(Expr(:tuple, args...)))...))))
       end
@myassign (macro with 1 method)

julia> @myassign(:x, f, 1,2,3,4)
sym = :(:x)
f = :f
args = (1, 2, 3, 4)
ERROR: syntax: invalid assignment location "(escape (inert x))"

I could let the macro return the function evaluation results but not for the assignment. I am completely lost in this. Could you please give me some clue to follow? Thanks in advance.

Perhaps this is an easier way to write it:

julia> macro myassign(sym, f, args...)
           return :($(esc(sym)) = $(esc(f))($(esc.(args)...)))
       end
@myassign (macro with 1 method)

julia> @macroexpand  @myassign(x, f, 1,2,3,4)
:(x = f(1, 2, 3, 4))
3 Likes

Thank you! Your solution clear my doubts and mess in my code.

Or with a single escape

macro myassign(sym, f, args...)
    :($sym = $f($(args...))) |> esc
end
1 Like