I want to be able to pass in a symbol which represents a function name into 
a macro and then have that function applied to an expression, something 
like:

  @apply_func :abs (x - y)

(where (x-y) could stand in for some expression or a single number)

I did a bit of searching here and came up with the following (posted by Tim 
Holy last year, from this post: 
https://groups.google.com/forum/#!searchin/julia-users/macro$20symbol/julia-users/lrtnyACdrxQ/5wovJmrUs0MJ
 
):

  macro apply_func(fn::Symbol, ex::Expr) 
     qex = Expr(:quote, ex) 
     quote 
       $(esc(fn))($qex) 
     end 
  end 

I've got a Symbol which represents a function name and I'd like to apply to 
the expression, so I'd like to be able to do:
   x = 10
   y = 11 
  @apply_func :abs (x - y)
...And get: 1

But first of all, a symbol doesn't work there:
julia> macroexpand(:(@apply_func :abs 1))
:($(Expr(:error, TypeError(:anonymous,"typeassert",Symbol,:(:abs)))))

I think this is because the arguments to the macro are already being passed 
in as a symbol... so it becomes ::abs

Ok, so what if I go with:

ulia> macroexpand(:(@apply_func abs 1+2))
  quote  # none, line 4:
      abs($(Expr(:copyast, :(:(1 + 2))))) 
  end

...that seems problematic because we're passing an Expr to the abs then:

julia> @apply_func abs 1+2
ERROR: `abs` has no method matching abs(::Expr)

Ok, so now I'm realizing that macro isn't going to do what I want it to, so 
let's change it:

  macro apply_func(fn::Symbol, ex::Expr)
     quote
       $(esc(fn))($ex)
     end
  end

That works better:
julia> @apply_func abs 1+2
3

But It won't work if I pass in a symbol:
julia> macroexpand(:(@apply_func :abs 1+2))
:($(Expr(:error, TypeError(:anonymous,"typeassert",Symbol,:(:abs)))))

How would I go about getting that case to work?

Phil



Reply via email to