# How to use an expression in a anonymous function?

**URL:** <https://discourse.julialang.org/t/how-to-use-an-expression-in-a-anonymous-function/27756>\
**Category:** General Usage\
**Tags:** question\
**Created:** [August 20, 2019, 12:02pm UTC](https://discourse.julialang.org/t/how-to-use-an-expression-in-a-anonymous-function/27756 "2019-08-20T12:02:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ufechner7](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ufechner7/32/51363_2.png) [@ufechner7](https://discourse.julialang.org/u/ufechner7)\
**Post date:** [August 20, 2019, 12:02pm UTC](https://discourse.julialang.org/t/how-to-use-an-expression-in-a-anonymous-function/27756/1 "2019-08-20T12:02:51Z")

</div>

The following works:

```julia
julia> map(x -> x^2 + 2x - 1, [1,3,-1])
3-element Array{Int64,1}:
  2
 14
 -2

```

But I need to calculate the function dynamically.

I have:

```julia
julia> expr=Meta.parse("x^2 + 2x - 1")
:((x ^ 2 + 2x) - 1)

```

Now I try to use this expression in a map operation,  
but it fails:

```julia
julia> map(x -> expr, [1,3,-1])
3-element Array{Expr,1}:
 :((x ^ 2 + 2x) - 1)
 :((x ^ 2 + 2x) - 1)
 :((x ^ 2 + 2x) - 1)

```

I tried to use eval but it doesn’t help.

```julia
julia> map(eval(x -> expr), [1,3,-1])
3-element Array{Expr,1}:
 :((x ^ 2 + 2x) - 1)
 :((x ^ 2 + 2x) - 1)
 :((x ^ 2 + 2x) - 1)

```

Any idea how to create an anonymous function from an expression that gives the same result as my first example?

Thank you!

Uwe

---

<div class="post-metadata">

**Author:** ![ufechner7](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ufechner7/32/51363_2.png) [@ufechner7](https://discourse.julialang.org/u/ufechner7)\
**Post date:** [August 20, 2019, 12:05pm UTC](https://discourse.julialang.org/t/how-to-use-an-expression-in-a-anonymous-function/27756/2 "2019-08-20T12:05:58Z")

</div>

Found the answer myself. The following works:

```julia
julia> expr=Meta.parse("x -> x^2 + 2x - 1")
:(x->begin
          #= none:1 =#
          (x ^ 2 + 2x) - 1
      end)
julia> map(eval(expr), [1,3,-1])
3-element Array{Int64,1}:
  2
 14
 -2

```

Sorry for the noise!
