Did you make any progress on this? I tried to do the exact same thing as 
you, got the exact same error, googled, and found this post. It seems that 
Julia parses default values for arguments separately from the name/type of 
the arguments. This was the macro I attempted:

macro optional(name, ptype)
    esc(:($name::Union(Nothing, $ptype) = nothing))
end

With the desired usage being:
function do_stuff(x::Int, y::String, @optional(z, Float))
    # do stuff
end

What I _really_ want (but I knew wouldn't be possible) would be:
function do_stuff(x::Int, y::String, z::@optional(Float))
    # do stuff
end

The Julia documentation 
at http://julia.readthedocs.org/en/latest/manual/metaprogramming/#hygiene 
makes the exaggerated claim "An expression wrapped in this manner is left 
alone by the macro expander and simply pasted into the output verbatim."

The documentation is clearly oversimplifying a bit, otherwise my macro 
should work.


On Friday, February 21, 2014 3:36:07 PM UTC-5, Joosep Pata wrote:
>
> Hi, 
>
> I’m trying to write a macro that would generate functions with optional 
> arguments. However, I can’t figure out why the following code behaves as it 
> does. I’d appreciate if someone told me what I’m doing wrong. 
>
> ~~~ 
> #1) def. value in quote, works 
> ex = :(x) 
> q = quote 
>         function f1($ex=1) 
>                 x 
>         end 
> end 
> macroexpand(q)|>println 
> eval(q) 
> f1()|>println 
>
>
> #2) def. value in expression, does not work 
> ex = :(x=1) 
> q = quote 
>         function f2($ex) 
>                 x 
>         end 
> end 
> println("does not work") 
> macroexpand(q)|>println 
> eval(q) 
> f2()|>println 
> ~~~ 
>
> 1) does not allow me to conveniently construct a list of arguments with 
> values, whereas 
> 2) gives me 
> > ERROR: syntax: "x=1" is not a valid function argument name 
>
> The macroexpand of either expression looks identical, except for spaces 
> around the “=“ sign for 2), which should not make a syntactical difference. 
>
> cheers, Joosep

Reply via email to