So the real question is how to generate a code block like this

quote
    x = 2
    y = 3
    .....
    x + y + ....
end

Need to embed a for loop inside the macro definition?


On Saturday, February 1, 2014 8:52:30 AM UTC-8, Walking Sparrow wrote:
>
> Please forgive me if this is a stupid question. Suppose I have an 
> expression
>
> :(sin(x) + cos(y) * sin(z))
>
> and the values of x, y, z.
>
> How can I write a macro that can substitute the values of x, y, z into the 
> above expression? The number of values that I want to substitute depends 
> on the actual use cases and thus is unknown.
>
> I wrote a function that can do this 
>
> function substitute(expr::Expr, vals::Array{Expr,1})
>     for i = 1:length(vals)
>         @eval $(vals[i])
>     end
>     @eval $expr
> end
>
> x = 10
> y = 23
>
> substitute(:(x+y), [:(x = 2), :(y = 3)])
>
> x
> y
>
> But if you run the above code, you will see that the values of global x 
> and y are changed, which is not what I intend to do. This is because "eval" 
> does the evaluation in the global scope. Besides, I think it is a bad 
> coding pattern to use eval and it is slow.
>
> It would be better if this can be done using macro. But I have no idea 
> about how to do this.
>

Reply via email to