Auto-evaluate function/expression in local scope

Instead of local variables, you could use a dictionary with symbols as keys that work as variable names. Then, you could make a macro that transforms formulas into functions that take such dictionaries:

using MacroTools

macro makefun(expr)
    new_expr = MacroTools.postwalk(expr) do subex
        if @capture(subex, :s_)
            return :(dic[$(QuoteNode(s))])
        else
            return subex
        end
    end
    return :( dic -> $new_expr )
end

f = @makefun :a + :b^2 + 20

variables = Dict()
for a = 1:10
	variables[:a] = a
	variables[:b] = a - 1
	println(f(variables))
end

Note: inspired in:

1 Like