# Metaprogramming: create function which takes arguments (vector and expression) to evaluate

**URL:** <https://discourse.julialang.org/t/metaprogramming-create-function-which-takes-arguments-vector-and-expression-to-evaluate/20965>\
**Category:** General Usage\
**Tags:** question\
**Created:** [February 19, 2019, 4:02am UTC](https://discourse.julialang.org/t/metaprogramming-create-function-which-takes-arguments-vector-and-expression-to-evaluate/20965 "2019-02-19T04:02:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jacob-roth](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jacob-roth/32/1862_2.png) [@jacob-roth](https://discourse.julialang.org/u/jacob-roth)\
**Post date:** [February 19, 2019, 4:02am UTC](https://discourse.julialang.org/t/metaprogramming-create-function-which-takes-arguments-vector-and-expression-to-evaluate/20965/1 "2019-02-19T04:02:31Z")

</div>

I have an expression `e = :(x[3] ^ 2.0)` that I hope to turn into a function which will evaluate `e` at `x` given arguments `e` and `x`. I tried the below but am messing something up.

```julia
function f(ex::Array{Float64,1}, expr::Expr)
    [x[i] = eval(ex[i]) for i =1:length(ex)]
    return eval(expr)
end

```

It differs slightly from [this](https://discourse.julialang.org/t/first-steps-to-metaprogramming/17715/3) question because my input is an array which I’m not sure how to loop over (I also tried the following)

```julia
function g(x)
    return :(x[3] ^ 2.0)
end
@eval function f(x)
    $(g(x))
end

```

---

<div class="post-metadata">

**Author:** ![c42f](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/c42f/32/52842_2.png) [@c42f](https://discourse.julialang.org/u/c42f)\
**Post date:** [February 19, 2019, 6:53am UTC](https://discourse.julialang.org/t/metaprogramming-create-function-which-takes-arguments-vector-and-expression-to-evaluate/20965/2 "2019-02-19T06:53:01Z")

</div>

Well, the first part of Kristoffer’s answer to the thread you linked is certainly relevant: it’s always worth asking whether you need metaprogramming at all. Why do you have an AST in this case rather than a function which you can use directly?

Anyway, to answer the question quite literally: If you must take an AST from somewhere and make a function from it:

```julia
function make_func(ex)
    # <-- Insert some validation that `ex` has the required form here.
    # Especially if `ex` is untrusted, you should whitelist allowed forms.
    g = gensym("myfunc")
    @eval function $g(x)
        $ex
    end
end

ex = :(x[3] ^ 2.0)
g = make_func(ex)

g([1,2,3])

```
