At some point in my program I create expressions (and store them inside variable (which is inside a struct)). At some later point I wish to do some light manipulations of these expressions and execute the resulting code. How do I do this?
ex = :(F(x)=2x+1)
exx_func = deepcopy(ex_func)
exx_func.args.args.args += 1
inc1 only sees the symbol
:ex, likvise if I try
$ex it only sees that, but not the content of the expression
Is this even possible/recommended with macros? I can achieve the same thing with a normal function and then an
eval at the end. However, when I first started with metaprogramming I learnt something about eval’s being dangerous and to avoid them.
No, what you’re trying to do is not possible with a macro. Macros only operate on the literal syntax they receive, so the symbol
:ex is all the macro has access to. On the other hand, it’s perfectly fine to write a function that operates on expressions, and there’s nothing inherently wrong with using
eval(). If you can provide more information about what you’re trying to do, we may be able to provide more specific advice about appropriate usage of
Wrote this but apparently didn’t subbmit it, rdeits wrote pretty much the same thing. Anyway:
Macros are syntactic transformations which doesn’t seem like what you want here.
eval can be dangerous but that is precisely because it allows you to dynamically execute arbitrary code (which it seems is what you need here).
DifferentialEquations.jl have several modelling tools which allows you to create models which are stored in structs and which can be used as input to simulations problems. One of these,
DiffEqBiological, generates a couple of expressions on use and stores them in the struct. I want to make a tool which modifies these expressions (which essentially are functions) and then evaluates them.