# Auto-evaluate function/expression in local scope

**URL:** <https://discourse.julialang.org/t/auto-evaluate-function-expression-in-local-scope/88515>\
**Category:** General Usage\
**Created:** [October 10, 2022, 9:31am UTC](https://discourse.julialang.org/t/auto-evaluate-function-expression-in-local-scope/88515 "2022-10-10T09:31:19Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![heliosdrm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/heliosdrm/32/3851_2.png) [@heliosdrm](https://discourse.julialang.org/u/heliosdrm)\
**Post date:** [October 10, 2022, 10:21am UTC](https://discourse.julialang.org/t/auto-evaluate-function-expression-in-local-scope/88515/3 "2022-10-10T10:21:17Z")

</div>

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:

```julia
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:

> [@Create Formulas with Macros](https://discourse.julialang.org/t/create-formulas-with-macros/87951):
>
> Hi all, I’m practicing working with macros and ran into an idea that I want to attempt to implement. Essentially, I want to create a macro @form that takes a formula expression. The expression would then be applied to a named tuple and return a new named tuple based on the formula values. Without a macro, I can achieve this with the following: # create named tuple nt = (; a =1, b=2) # function of interest formulafun(nt) =(:a, nt[:a] + nt[:b] +1) function foo(nt, formulafun) operation…

---

_[View the full topic](https://discourse.julialang.org/t/auto-evaluate-function-expression-in-local-scope/88515)._
