You need to provide more detail on what you are trying to do with this. You seem to be confusing several concepts involving the usage of expressions, macros, and functions. I can't tell if you are trying to write special syntax, or are just unaware of anonymous functions:
Mostly, why is :(sin(x) + cos(y) * sin(z)) an expression, and not a function? It seems like you perhaps have an R background? f(x,y,z) = (sin(x) + cos(y) * sin(z)) f(1,2,3) On Sat, Feb 1, 2014 at 12:04 PM, Walking Sparrow <[email protected]> wrote: > 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.
