You don't even need a macro if it's a one-off thing – you can just generate
the AST for the function definition and then eval it. Building AST and
calling eval has the advantage that you don't need to worry about macro
hygiene, which is not that hard but kind of annoying. As mentioned, the chapter
on metaprogramming
<http://docs.julialang.org/en/stable/manual/metaprogramming/> has a fair
amount of detail on how to go about doing this.

On Sat, Dec 26, 2015 at 3:08 PM, Josh Langsfeld <[email protected]> wrote:

> As Yichao is hinting, you may find a macro to be a cleaner way of making
> your functions instead of constructing and parsing a string.
>
> macro return_fcn(N)
>     xexprs = Expr[:($(symbol(:x,i)) = X[$i]) for i=1:N]
>     return esc(:(
>         function $(symbol(:f,N))(X::Vector)
>             $(xexprs...)
>             mu = X[$(N+1)]
>         end
>     ))
> end
>
> julia> macroexpand(:(@return_fcn(2)))
> :(function f2(X::Vector)
>         x1 = X[1]
>         x2 = X[2]
>         mu = X[3]
>     end)
>
> julia> macroexpand(:(@return_fcn(4)))
> :(function f4(X::Vector)
>         x1 = X[1]
>         x2 = X[2]
>         x3 = X[3]
>         x4 = X[4]
>         mu = X[5]
>     end)
>
>
>
> On Saturday, December 26, 2015 at 2:03:56 PM UTC-5, Stuart Brorson wrote:
>>
>> Julia users,
>>
>> I'm fiddling around with Julia's strings & metaprogramming.  I am
>> constructing a function by concatenating a bunch of strings together
>> to create my function, like this:
>>
>> function return_fcn(N)
>>    P = string("function f$N(X::Vector)\n")
>>    for i in 1:N
>>      P = string(P, "x$i = X[$i];\n");
>>    end
>>    P = string(P, "mu = X[$(N+1)];\n")
>>    etc....
>>
>> When I execute this code, I get:
>>
>> julia> y = return_fcn(2)
>> "function f2(X::Vector)\nx1 = X[1];\nx2 = X[2];\nmu = X[3];\n"
>>
>> However, what I really want to see is
>>
>> function f2(X::Vector)
>> x1 = X[1];
>> x2 = X[2];
>> mu = X[3];
>>
>> "show(y)" doesn't seem to do what I want.  Later, when I do
>>
>> eval(parse(y))
>>
>> then I get a function which executes correctly.  My problem is simply
>> that I can't get Julia to give me a string I can read easily.  This
>> will be a very big issue for me when N -> 1024, 2048, etc....
>>
>> Questions:
>>
>> 1.  How can I escape the \n to get a real <CR><LF> in my displayed
>> string?
>>
>> 2.  Is this the optimal way to construct a program for later execution
>> (i.e. metaprogramming)?
>>
>> Thanks for all wisdom you have to offer.
>>
>> Stuart
>>
>

Reply via email to